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

后端 未结 11 1636
礼貌的吻别
礼貌的吻别 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: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();
    

提交回复
热议问题