PHP 创建嵌套目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6579936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP create nested directories
提问by sunjie
I need help with a function to create a 2 level directory for the following situations:
我需要有关为以下情况创建 2 级目录的函数的帮助:
- 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.
- 所需的子目录存在于父目录中,什么都不做。
- 父目录存在,子目录不存在。仅创建子目录。
- 父目录和子目录都不存在,先创建父目录,再创建子目录。
- 如果任何目录未成功创建,则返回 FALSE。
Thanks for the help.
谢谢您的帮助。
回答by KingCrunch
回答by Ramyz
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!!
recursive 允许创建路径名中指定的嵌套目录。但对我不起作用!!因为这就是我想出的!!它工作得非常完美!!
$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
}
}
回答by Balanivash
you can try using file_existsto check if a folder exists or not and is_dir
to check if it is a folder or not.
您可以尝试使用file_exists来检查文件夹是否存在并is_dir
检查它是否是文件夹。
if(file_exists($dir) && is_dir($dir))
And to create a directory you can use the mkdir
function
并创建一个目录,您可以使用该mkdir
功能
Then the rest of your question is just manipulating this to suit the requirements
然后你的其余问题只是操纵它以满足要求
回答by T.Todua
How much i suffered.. and got this script..
我受了多少苦..得到了这个剧本..
function recursive_mkdir($dest, $permissions=0755, $create=true){
if(!is_dir(dirname($dest))){ recursive_mkdir(dirname($dest), $permissions, $create); }
elseif(!is_dir($dest)){ mkdir($dest, $permissions, $create); }
else{return true;}
}
回答by monsieur_h
The function you're looking for is MKDIR. Use the last parameter to recursively create directories. And read the documentation.
您正在寻找的功能是 MKDIR。使用最后一个参数递归创建目录。并阅读文档。
回答by Simon
回答by Andi T
// Desired folder structure
$structure = './depth1/depth2/depth3/';
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0744, true)) {
die('Failed to create folders...');
}
Returns TRUE on success or FALSE on failure.