我想创建一个目录,如果它不存在。

使用is_dir函数就足够了吗?

if ( !is_dir( $dir ) ) {
    mkdir( $dir );       
}

或者我应该结合is_dir与file_exists?

if ( !file_exists( $dir ) && !is_dir( $dir ) ) {
    mkdir( $dir );       
} 

当前回答

$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;
}

其他回答

我也有同样的疑问,但请参阅PHP文档:

https://www.php.net/manual/en/function.file-exists.php

https://www.php.net/manual/en/function.is-dir.php

您将看到is_dir()具有这两个属性。

返回值is_dir 如果文件名存在且为目录,则返回TRUE,否则返回FALSE。

检查路径是否为directory的方法如下:

function isDirectory($path) {
    $all = @scandir($path);
    return $all !== false;
}

注意:对于不存在的路径,它也会返回false,但是对于UNIX/Windows非常有效

$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;
}

这是一个老问题,但仍然是热门话题。只需要使用is_dir()或file_exists()函数测试是否存在。或. .在测试目录中的文件。每个目录必须包含以下文件:

is_dir("path_to_directory/.");    

我就是这么做的

if(is_dir("./folder/test"))
{
  echo "Exist";
}else{
  echo "Not exist";
}