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:
class Explorer
{ public static function makeFoldersFromFilepath
($szFilepath,
$szSeperator = DIRECTORY_SEPARATOR
) { $aParts =
explode($szSeperator,
$szFilepath);
$szLevels =
null;
$aLevels =
array();
foreach ($aParts as $szPart) { $szParentLevels =
implode($szSeperator,
$aLevels);
$aLevels[] =
$szPart;
$szLevels =
implode($szSeperator,
$aLevels);
if (preg_match('~:$~i',
$szPart) ||
is_dir($szLevels)) { continue;
} if (!
is_writeable($szParentLevels)) { throw
new Exception
('Cannot create folder "' .
$szLevels .
'" because its parent is not writeable');
} if (!
mkdir($szLevels)) { throw
new Exception
('Cannot create folder "' .
$szLevels .
'" for an unknown reason');
} } }}