![]() |
Creating directory hierarchies with ease
I created this function today because we desperately needed a solution to save on repeated code. Such as checking if the directory exists, and if not creating it. Then looping through again and seeing if that exists, etcetera, etcetera.
The function I came up with accepts a directory path. For example: C:\wamp\www\images\TalkPHP\screenshots\. It will then loop through all the directories, ignoring things like C: and D: on Windows. If a particular directory doesn't exist then it will create it for you. If its parent is not writeable, then it will throw an exception telling you so. I'm not overly keen on the subsequent exception, and you may also need to prepend @ in front of mkdir to suppress nasty PHP errors.I am more than open to suggestions for improving this function, and that's half the reason I'm releasing it to the public. The other half is because it's a truly useful function! By all means, use it wherever you like! The second argument for the function (Default: DIRECTORY_SEPARATOR) is a native PHP constant for detecting the backslash type depending on the operating system. This, of course, can be modified by specifying the second argument upon calling the function.Without further ado: php Code:
|
In PHP 5
mkdir has the third argument of (bool) recursive (default FALSE). Couple that with the ability to specify the mode and to apply a context (neither of which you class can do) I'm not seeing any advantage of your class over calling the mkdir function normally.That said, maybe I'm just entirely missing the point. :-/ |
Nice share wildhoney.
|
Thank you. Although as Salathe pointed out (smug git! :-)) the PHP manual should always be read first. I simply assumed that they'd not yet added the recursive mode, but it would appear they added it in PHP 5.0.0, and fixed the last bug with version 5.2.0.
Nonetheless, I still prefer the throwing of exceptions if PHP is unable to create the directory. That probably doesn't necessitate a rewrite, however. |
| All times are GMT. The time now is 10:47 AM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0