Search code examples
phpmkdirchdir

Find out if a directory exists in php


I want to know whether or not a directory exists.

If not, I would like to create the directory.

My code is below:

$da = getdate();
$dat = $da["year"]."-".$da["mon"]."-".$da["mday"];
$m = md5($url)."xml";
if(is_dir($dat))
{
    chdir($dat);
    $fh = fopen($m, 'w');
    fwrite($fh, $xml); 
    fclose($fh);
    echo "yes";
}
else
{
    mkdir($dat,0777,true); 
    chdir($dat);   
    $fh = fopen($m, 'w');   
    fwrite($fh, $xml);    
    fclose($fh); 
    echo "not";
} 

Solution

  • Use is_dir, which checks whether the path exists and is a directory then mkdir.

    function mkdir_if_not_there($path) {
      if (!is_dir($path)) {
        // Watch out for potential race conditions here
        mkdir($path);
      }
    }