PHP create nested directories
Solution 1
Use the third parameter of mkdir()
:
recursive Allows the creation of nested directories specified in the pathname. Defaults to FALSE.
$path = '/path/to/folder/with/subdirectory';
mkdir($path, 0777, true);
Solution 2
recursive Allows the creation of nested directories specified in the pathname. but did not work for me!! for that here is what i came up with!! and it work very perfect!!
$upPath = "../uploads/RS/2014/BOI/002"; // full path
$tags = explode('/' ,$upPath); // explode the full path
$mkDir = "";
foreach($tags as $folder) {
$mkDir = $mkDir . $folder ."/"; // make one directory join one other for the nest directory to make
echo '"'.$mkDir.'"<br/>'; // this will show the directory created each time
if(!is_dir($mkDir)) { // check if directory exist or not
mkdir($mkDir, 0777); // if not exist then make the directory
}
}
Solution 3
you can try using file_exists to check if a folder exists or not and is_dir
to check if it is a folder or not.
if(file_exists($dir) && is_dir($dir))
And to create a directory you can use the mkdir
function
Then the rest of your question is just manipulating this to suit the requirements
Solution 4
See mkdir
, in particular the $recursive
parameter.
Solution 5
Starting with PHP 8 (2020-11-24), you can use named parameters:
<?php
mkdir('March/April', recursive: true);
sunjie
Updated on November 26, 2020Comments
-
sunjie over 3 years
I need help with a function to create a 2 level directory for the following situations:
- The desired sub-directory exists in the parent directory, do nothing.
- Parent directory exists, sub-directory does not exist. Create only the sub-directory.
- Neither parent directory, nor the sub-directory exists, First create parent directory, then sub-directory.
- If Any of the directory was not created successfully, return FALSE.
Thanks for the help.
-
KingCrunch about 9 years@Paulocoghi You are right. This behaviour is different from Linux'
mv
, which simply ignores existing paths -
Thyagi over 8 yearsuse if(!is_dir($path)) { mkdir($path, 0777, true); }
-
Buffalo over 3 yearsIs this just not formatted or do you seriously write code like this?
-
T.Todua over 3 years@buffalo, if had seriously read the information about answer (either my comment
got this script
or even post date) it says enough. moreover, you could just edit post, instead of irony, you had enough rep ;) cheers.