我需要有关为以下情况创建 2 级目录的功能的帮助:
- 所需的子目录存在于父目录中,什么也不做。
- 父目录存在,子目录不存在。仅创建子目录。
- 父目录和子目录都不存在,先创建父目录,再创建子目录。
- 如果任何目录没有成功创建,则返回 FALSE。
谢谢您的帮助。
使用的第三个参数mkdir()
:
recursive允许创建在路径名中指定的嵌套目录。默认为假。
$path = '/path/to/folder/with/subdirectory';
mkdir($path, 0777, true);
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
}
}
您可以尝试使用file_exists来检查文件夹是否存在并is_dir
检查它是否是文件夹。
if(file_exists($dir) && is_dir($dir))
并且要创建一个目录,您可以使用该mkdir
功能
那么你剩下的问题就是操纵它来满足要求
参见mkdir
,特别是$recursive
参数。
我受了多少苦……得到了这个剧本……
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;}
}
从 PHP 8 (2020-11-24) 开始,您可以使用命名参数:
<?php
mkdir('March/April', recursive: true);
您正在寻找的功能是 MKDIR。使用最后一个参数递归地创建目录。并阅读文档。
从 PHP 5.0+开始, mkdir有一个递归参数,它将创建任何缺少的父级。
// 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.