php 如何检查目录是否存在?“is_dir”、“file_exists”还是两者兼而有之?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5425891/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:22:22  来源:igfitidea点击:

How do I check if a directory exists? "is_dir", "file_exists" or both?

php

提问by Peter

I want to create a directory if it does'nt exist already.

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

Is using is_direnough for that purpose?

is_dir为此目的使用足够了吗?

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

Or should I combine is_dirwith file_exists?

或者我应该is_dirfile_exists?

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

采纳答案by Marc B

Both would return true on Unix systems - in Unix everything is a file, including directories. But to test if that name is taken, you should check both. There might be a regular file named 'foo', which would prevent you from creating a directory name 'foo'.

在 Unix 系统上两者都会返回 true - 在 Unix 中一切都是文件,包括目录。但是要测试是否使用了该名称,您应该同时检查两者。可能有一个名为“foo”的常规文件,它会阻止您创建目录名称“foo”。

回答by Maher

$dirname = $_POST["search"];
$filename = "/folder/" . $dirname . "/";

if (!file_exists($filename)) {
    mkdir("folder/" . $dirname, 0777);
    echo "The directory $dirname was successfully created.";
    exit;
} else {
    echo "The directory $dirname exists.";
}

回答by inckie

I think realpath() may be the best way to validate if a path exist http://www.php.net/realpath

我认为 realpath() 可能是验证路径是否存在的最佳方法 http://www.php.net/realpath

Here is an example function:

这是一个示例函数:

<?php
/**
 * Checks if a folder exist and return canonicalized absolute pathname (long version)
 * @param string $folder the path being checked.
 * @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
 */
function folder_exist($folder)
{
    // Get canonicalized absolute pathname
    $path = realpath($folder);

    // If it exist, check if it's a directory
    if($path !== false AND is_dir($path))
    {
        // Return canonicalized absolute pathname
        return $path;
    }

    // Path/folder does not exist
    return false;
}

Short version of the same function

相同功能的简短版本

<?php
/**
 * Checks if a folder exist and return canonicalized absolute pathname (sort version)
 * @param string $folder the path being checked.
 * @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
 */
function folder_exist($folder)
{
    // Get canonicalized absolute pathname
    $path = realpath($folder);

    // If it exist, check if it's a directory
    return ($path !== false AND is_dir($path)) ? $path : false;
}

Output examples

输出示例

<?php
/** CASE 1 **/
$input = '/some/path/which/does/not/exist';
var_dump($input);               // string(31) "/some/path/which/does/not/exist"
$output = folder_exist($input);
var_dump($output);              // bool(false)

/** CASE 2 **/
$input = '/home';
var_dump($input);
$output = folder_exist($input);         // string(5) "/home"
var_dump($output);              // string(5) "/home"

/** CASE 3 **/
$input = '/home/..';
var_dump($input);               // string(8) "/home/.."
$output = folder_exist($input);
var_dump($output);              // string(1) "/"

Usage

用法

<?php

$folder = '/foo/bar';

if(FALSE !== ($path = folder_exist($folder)))
{
    die('Folder ' . $path . ' already exist');
}

mkdir($folder);
// Continue do stuff

回答by Boolean_Type

Second variant in question post is not ok, because, if you already have file with the same name, but it is not a directory, !file_exists($dir)will return false, folder will not be created, so error "failed to open stream: No such file or directory"will be occured. In Windows there is a difference between 'file' and 'folder' types, so need to use file_exists()and is_dir()at the same time, for ex.:

有问题的第二个变体是不行的,因为,如果您已经有同名的文件,但它不是目录,!file_exists($dir)将返回false,将不会创建文件夹,因此"failed to open stream: No such file or directory"会发生错误。在 Windows 中,'file' 和 'folder' 类型是有区别的,所以需要同时使用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);
}

回答by hour man

$save_folder = "some/path/" . date('dmy');

if (!file_exists($save_folder)) {
   mkdir($save_folder, 0777);
}

回答by rons

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

回答by Sujeet Kumar

add true after 0777

在 0777 之后添加 true

<?php
    $dirname = "small";
    $filename = "upload/".$dirname."/";

    if (!is_dir($filename )) {
        mkdir("upload/" . $dirname, 0777, true);
        echo "The directory $dirname was successfully created.";
        exit;
    } else {
        echo "The directory $dirname exists.";
    }
     ?>

回答by Sebas

Well instead of checking both, you could do if(stream_resolve_include_path($folder)!==false). It is slowerbut kills two birds in one shot.

那么你可以做if(stream_resolve_include_path($folder)!==false). 它速度较慢,但一枪杀死两只鸟。

Another option is to simply ignore the E_WARNING, notby using @mkdir(...);(because that would simply waive all possible warnings, not just the directory already exists one), but by registering a specific error handler before doing it:

另一种选择是简单地忽略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();

回答by djordje

This is an old, but still topical question. Just test with the is_dir()or file_exists()function for the presence of the .or ..file in the directory under test. Each directory must contain these files:

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

is_dir("path_to_directory/.");    

回答by Jetro Bernardo

This is how I do

这就是我的做法

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