1

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";
} 
gnat
  • 6,213
  • 108
  • 53
  • 73
zahir hussain
  • 3,711
  • 10
  • 29
  • 36

2 Answers2

7

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);
  }
}
Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
0

Use is_dir:

$pathname = "/path/to/dir";
if(is_dir($pathname)) {
   // do something
}
Joe Mastey
  • 26,809
  • 13
  • 80
  • 104