wp_mkdir_p

Recursive directory creation based on full path.

Description

wp_mkdir_p( (string) $target ); 

Will attempt to set permissions on folders.

Parameters (1)

0. $target (string)
Full path to attempt to create.

Usage

  1. if ( !function_exists( 'wp_mkdir_p' ) ) { 
  2. require_once ABSPATH . WPINC . '/functions.php'; 
  3.  
  4. // Full path to attempt to create. 
  5. $target = ''; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = wp_mkdir_p($target); 
  9.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/functions.php  
  1. function wp_mkdir_p( $target ) { 
  2. $wrapper = null; 
  3.  
  4. // Strip the protocol. 
  5. if ( wp_is_stream( $target ) ) { 
  6. list( $wrapper, $target ) = explode( '://', $target, 2 ); 
  7.  
  8. // From php.net/mkdir user contributed notes. 
  9. $target = str_replace( '//', '/', $target ); 
  10.  
  11. // Put the wrapper back on the target. 
  12. if ( $wrapper !== null ) { 
  13. $target = $wrapper . '://' . $target; 
  14.  
  15. /** 
  16. * Safe mode fails with a trailing slash under certain PHP versions. 
  17. * Use rtrim() instead of untrailingslashit to avoid formatting.php dependency. 
  18. */ 
  19. $target = rtrim($target, '/'); 
  20. if ( empty($target) ) 
  21. $target = '/'; 
  22.  
  23. if ( file_exists( $target ) ) 
  24. return @is_dir( $target ); 
  25.  
  26. // We need to find the permissions of the parent folder that exists and inherit that. 
  27. $target_parent = dirname( $target ); 
  28. while ( '.' != $target_parent && ! is_dir( $target_parent ) ) { 
  29. $target_parent = dirname( $target_parent ); 
  30.  
  31. // Get the permission bits. 
  32. if ( $stat = @stat( $target_parent ) ) { 
  33. $dir_perms = $stat['mode'] & 0007777; 
  34. } else { 
  35. $dir_perms = 0777; 
  36.  
  37. if ( @mkdir( $target, $dir_perms, true ) ) { 
  38.  
  39. /** 
  40. * If a umask is set that modifies $dir_perms, we'll have to re-set 
  41. * the $dir_perms correctly with chmod() 
  42. */ 
  43. if ( $dir_perms != ( $dir_perms & ~umask() ) ) { 
  44. $folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) ); 
  45. for ( $i = 1, $c = count( $folder_parts ); $i <= $c; $i++ ) { 
  46. @chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms ); 
  47.  
  48. return true; 
  49.  
  50. return false;