note 60825 deleted from function.mkdir by felipe
| From: | felipe@php.net | Date: | Mon, 10 Dec 2007 18:11:39 +0000 |
| Subject: | note 60825 deleted from function.mkdir by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-133256@lists.php.net to get a copy of this message | ||
Note Submitter: baldurien at club-internet dot fr
----
For those wandering about the $recursive flag of mkdir in php5, this function will do what you want
(à la java) in php 4:
<?php
/**
* Create a new directory, and the whole path.
*
* If the parent directory does not exists, we will create it,
* etc.
*
* @param string the directory to create
* @param int the mode to apply on the directory
* @return bool return true on success, false else
*/
function mkdirs($dir, $mode = FS_RIGHTS_D) {
$stack = array(basename($dir));
$path = null;
while ( ($d = dirname($dir) ) ) {
if ( !is_dir($d) ) {
$stack[] = basename($d);
$dir = $d;
} else {
$path = $d;
break;
}
}
if ( ( $path = realpath($path) ) === false )
return false;
$created = array();
for ( $n = count($stack) - 1; $n >= 0; $n-- ) {
$s = $path . '/'. $stack[$n];
if ( !mkdir($s, $mode) ) {
for ( $m = count($created) - 1; $m >= 0; $m-- )
rmdir($created[$m]);
return false;
}
$created[] = $s;
$path = $s;
}
return true;
}
?>
The main idea here is to use a stack to store the invalid dirname (using basename/dirname), and then
pop each item on the stack to create directory from a valid path (here: $path = realpath($path). If
we fails creating one directory, we must remove them in the reverse order of creation (stackes :)).
This works on Windows XP, and it should work on Linux (actually, I did not tested it).
Note that this code is a part of one of my classes (named FileSystem), and that you should use your
own basename/realpath/dirname/mkdir/rmdir function instead of php one (even if you use them behind).
This will allow you to separate the item of a FileSystem from what is it really (FTP? Local ?
Telnet? Teletubbies?)