我想创建一个目录,如果它不存在。
使用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;
}
$save_folder = "some/path/" . date('dmy');
if (!file_exists($save_folder)) {
mkdir($save_folder, 0777);
}
我就是这么做的
if(is_dir("./folder/test"))
{
echo "Exist";
}else{
echo "Not exist";
}
我认为这是dir检查的快速解决方案。
$path = realpath($Newfolder);
if (!empty($path)){
echo "1";
}else{
echo "0";
}
$year = date("Y");
$month = date("m");
$filename = "../".$year;
$filename2 = "../".$year."/".$month;
if(file_exists($filename)){
if(file_exists($filename2)==false){
mkdir($filename2,0777);
}
}else{
mkdir($filename,0777);
}