如何檢查目錄是否存在? “ is_dir”,“ file_exists”還是兩者?

本文翻譯自:How do I check if a directory exists? “is_dir”, “file_exists” or both?

I want to create a directory if it does'nt exist already. 如果目錄尚不存在,我想創建一個目錄。

Is using is_dir enough for that purpose? 使用is_dir是否足以達到目的?

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

Or should I combine is_dir with file_exists ? 還是應該將is_dirfile_exists結合使用?

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

#1樓

參考:https://stackoom.com/question/MlWN/如何檢查目錄是否存在-is-dir-file-exists-還是兩者


#2樓

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

#3樓

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

#4樓

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

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

#5樓

Well instead of checking both, you could do if(stream_resolve_include_path($folder)!==false) . 好吧,而不是同時檢查兩者,您可以執行if(stream_resolve_include_path($folder)!==false) It is slower but kills two birds in one shot. 它的速度較慢,但一槍殺死了兩隻鳥。

Another option is to simply ignore the E_WARNING , not by using @mkdir(...); 另一種選擇是簡單地忽略E_WARNING而不使用@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: (因爲這將簡單地放棄所有可能的警告,不僅僅是目錄已經存在),而是通過在執行操作之前註冊一個特定的錯誤處理程序來進行:

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();

#6樓

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. 有問題的帖子的第二個變種不好,因爲,如果您已經有相同名稱的文件,但它不是目錄,則!file_exists($dir)將返回false ,將不會創建文件夾,因此錯誤"failed to open stream: No such file or directory" 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.: 在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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章