a PHP function to create directories recursively.

simply call this function with a path and it will attempt to create all missing directories recursively.

returns array with verbose report.

recursive make directory” makes use of the built-in PHP functions getcwd( ), explode( ), count( ), is_writeable( ), file_exists( ), mkdir( ) and print_r( ).

01 <?php
02 
03 function recursive_mkdir($new_path,$permissions=0777)
04 {
05     $current_directory = getcwd();
06     $report = array('working in &quot;'.$current_directory.'&quot;');
07     $report[] = 'attempting to create &quot;'.$current_directory.'/'.$new_path.'&quot;';
08     $directories = explode('/',$new_path);
09     $new_path_str = $current_directory;
10     $n = $cn = count($directories);
11     foreach($directories as $directory)
12     {
13         if(!is_writeable($new_path_str))
14         {
15             $report[] = '&quot;'.$new_path_str.'&quot; is not writeable';
16             $report[] = 'aborting recursive mkdir()';
17             return $report;
18         }
19         $new_path_str .= '/'.$directory;
20         if(!file_exists($new_path_str))
21         {
22             $report[] = (mkdir($new_path_str,$permissions) ? 
23                 'created' : 'failed to create').' &quot;'.$new_path_str.'&quot;';
24         }else{
25             $report[] = 'skipped &quot;'.$new_path_str.'&quot;';
26             $cn--;
27         }
28     }
29     $report[] = 'created '.$cn.' of '.$n.' directories';
30     return $report;
31 }
32  
33  
34 // example
35 echo '<pre>';
36 print_r(recursive_mkdir('test/directory/new/folder'));
37 echo '</pre>';
38  
39 ?>