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

后端 未结 11 1564
礼貌的吻别
礼貌的吻别 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:16

    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("path_to_directory/.");    
    
    0 讨论(0)
  • 2020-11-28 19:23

    A way to check if a path is directory can be following:

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

    NOTE: It will return false for non-existant path too, but works perfectly for UNIX/Windows

    0 讨论(0)
  • 2020-11-28 19:24
    $save_folder = "some/path/" . date('dmy');
    
    if (!file_exists($save_folder)) {
       mkdir($save_folder, 0777);
    }
    
    0 讨论(0)
  • 2020-11-28 19:25

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

    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);
    }
    
    0 讨论(0)
  • 2020-11-28 19:25
    $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);
    }
    
    0 讨论(0)
  • 2020-11-28 19:31

    This is how I do

    if(is_dir("./folder/test"))
    {
      echo "Exist";
    }else{
      echo "Not exist";
    }
    
    0 讨论(0)
提交回复
热议问题