note 63406 added to function.mkdir
| From: | bat at flurf dot net | Date: | Wed, 22 Mar 2006 05:23:57 +0000 |
| Subject: | note 63406 added to function.mkdir | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-106205@lists.php.net to get a copy of this message | ||
A little understanding of LISPlike programming makes this sort of task (recursive mkdir()ing in
PHP4) much simpler. This version works nicely:
<?php
function MakeDirectory($dir, $mode = 0755)
{
if (is_dir($dir) || @mkdir($dir,$mode)) return TRUE;
if (!MakeDirectory(dirname($dir),$mode)) return FALSE;
return @mkdir($dir,$mode);
}
?>
How it works: line one attempts to make the directory, and returns TRUE if it works or if it already
exists. That's the easy case if the parent directories all exist.
Line two trims off the last directory name using dirname(), and calls MakeDirectory recursively on
that shorter directory. If that fails, it returns FALSE, but otherwise we come out of it knowing
that the parent directory definitely exists.
Finally, presuming the recursive call worked, once we get to line three we can create the requested
directory.
Note the use of @ to suppress warning messages from mkdir.
The beauty of this is that if, say, the great-grandparent directory exists but the grandparent and
parent directories don't, the function will simply call itself recursively until it gets high
enough up the tree to do some work, then carry on unwinding back until all the new directories have
been created.
This is pretty bog-standard recursive programming. Anyone who can't wrap their head around it
after a few minutes of concentration should probably try a career in sales.
----
Server IP: 203.16.234.91
Probable Submitter: 152.91.8.100 (proxied: unknown)
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/function.mkdir.php
Edit -- http://master.php.net/note/edit/63406
Del: integrated -- http://master.php.net/note/delete/63406/integrated
Del: useless -- http://master.php.net/note/delete/63406/useless
Del: bad code -- http://master.php.net/note/delete/63406/bad+code
Del: spam -- http://master.php.net/note/delete/63406/spam
Del: non-english -- http://master.php.net/note/delete/63406/non-english
Del: in docs -- http://master.php.net/note/delete/63406/in+docs
Del: other reasons-- http://master.php.net/note/delete/63406
Reject -- http://master.php.net/note/reject/63406
Search -- http://master.php.net/manage/user-notes.php