我想创建一个目录,如果它不存在。
使用is_dir函数就足够了吗?
if ( !is_dir( $dir ) ) {
mkdir( $dir );
}
或者我应该结合is_dir与file_exists?
if ( !file_exists( $dir ) && !is_dir( $dir ) ) {
mkdir( $dir );
}
我想创建一个目录,如果它不存在。
使用is_dir函数就足够了吗?
if ( !is_dir( $dir ) ) {
mkdir( $dir );
}
或者我应该结合is_dir与file_exists?
if ( !file_exists( $dir ) && !is_dir( $dir ) ) {
mkdir( $dir );
}
当前回答
好吧,而不是检查两者,你可以这样做if(stream_resolve_include_path($folder)!==false)。它速度较慢,但能一枪打死两只鸟。
另一个选择是忽略E_WARNING,而不是使用@mkdir(…);(因为这将简单地放弃所有可能的警告,不仅仅是目录已经存在一个),而是通过注册一个特定的错误处理程序,然后再这样做:
namespace com\stackoverflow;
set_error_handler(function($errno, $errm) {
if (strpos($errm,"exists") === false) throw new \Exception($errm); //or better: create your own FolderCreationException class
});
mkdir($folder);
/* possibly more mkdir instructions, which is when this becomes useful */
restore_error_handler();
其他回答
$filename = "/folder/" . $dirname . "/";
if (file_exists($filename)) {
echo "The directory $dirname exists.";
} else {
mkdir("folder/" . $dirname, 0755);
echo "The directory $dirname was successfully created.";
exit;
}
好吧,而不是检查两者,你可以这样做if(stream_resolve_include_path($folder)!==false)。它速度较慢,但能一枪打死两只鸟。
另一个选择是忽略E_WARNING,而不是使用@mkdir(…);(因为这将简单地放弃所有可能的警告,不仅仅是目录已经存在一个),而是通过注册一个特定的错误处理程序,然后再这样做:
namespace com\stackoverflow;
set_error_handler(function($errno, $errm) {
if (strpos($errm,"exists") === false) throw new \Exception($errm); //or better: create your own FolderCreationException class
});
mkdir($folder);
/* possibly more mkdir instructions, which is when this becomes useful */
restore_error_handler();
检查路径是否为directory的方法如下:
function isDirectory($path) {
$all = @scandir($path);
return $all !== false;
}
注意:对于不存在的路径,它也会返回false,但是对于UNIX/Windows非常有效
第二个变量在问题post是不行的,因为,如果你已经有同名的文件,但它不是一个目录,!file_exists($dir)将返回false,文件夹将不会被创建,所以错误“failed to open stream: No such file or directory”将会发生。在Windows中,'文件'和'文件夹'类型是不同的,因此需要同时使用file_exists()和is_dir(),例如:
if (file_exists('file')) {
if (!is_dir('file')) { //if file is already present, but it's not a dir
//do something with file - delete, rename, etc.
unlink('file'); //for example
mkdir('file', NEEDED_ACCESS_LEVEL);
}
} else { //no file exists with this name
mkdir('file', NEEDED_ACCESS_LEVEL);
}
我就是这么做的
if(is_dir("./folder/test"))
{
echo "Exist";
}else{
echo "Not exist";
}