PHP: Recursive Create Path (if not exists)
Jul 31, 2008 · 1 minute readCategory: php
This is post is now quite old and the the information it contains may be out of date or innacurate.
If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub
If you pass a path with a filename at teh end, set the second parameter to true eg make_path($path, true)
/*Create Directory Tree if Not Exists
If you are passing a path with a filename on the end, pass true as the second parameter to snip it off */
function make_path($pathname, $is_filename=false){
if($is_filename){
$pathname = substr($pathname, 0, strrpos($pathname, '/'));
}
// Check if directory already exists
if (is_dir($pathname) || empty($pathname)) {
return true;
}
// Ensure a file does not already exist with the same name
$pathname = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $pathname);
if (is_file($pathname)) {
trigger_error('mkdirr() File exists', E_USER_WARNING);
return false;
}
// Crawl up the directory tree
$next_pathname = substr($pathname, 0, strrpos($pathname, DIRECTORY_SEPARATOR));
if (make_path($next_pathname, $mode)) {
if (!file_exists($pathname)) {
return mkdir($pathname, $mode);
}
}
return false;
}