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

后端 未结 11 1565
礼貌的吻别
礼貌的吻别 2020-11-28 18:36

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

Is using is_dir enough for that purpose?

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


        
相关标签:
11条回答
  • 2020-11-28 19:34

    I think realpath() may be the best way to validate if a path exist 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
    
    0 讨论(0)
  • 2020-11-28 19:36

    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'.

    0 讨论(0)
  • 2020-11-28 19:36

    Well instead of checking both, you could do 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(...); (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();
    
    0 讨论(0)
  • 2020-11-28 19:37
    $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.";
    }
    
    0 讨论(0)
  • 2020-11-28 19:42

    I had the same doubt, but see the PHP docu:

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

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

    You will see that is_dir() has both properties.

    Return Values is_dir Returns TRUE if the filename exists and is a directory, FALSE otherwise.

    0 讨论(0)
提交回复
热议问题