tags:

views:

65

answers:

3

How can i test if a directory already exist and if not create one in PHP?

+2  A: 

Try this:

$filename = "/tmp";
if (!file_exists($filename))
    echo $filename, " does not exist";
elseif (!is_dir($filename))
    echo $filename, " is not a directory";
else
    echo "Directory ", $filename, " already exists";

file_exists checks if the path/file exists and is_dir checks whether the given filename is a directory.

Edit:

to create the directory afterwards, call

mkdir($filename);
Cassy
The call to file_exists(...) is not necessary. is_dir(...) will return false if it does not exist.
Mike
I would say the same, but he said 'is_dir doesnt work for me'
DaNieL
`file_exists` should be called anyway if the next step is to create a directory with the given name. If there was a file named exactly like the target directory, a call to `mkdir` would fail although the "directory" was not there...
Cassy
Yeah unfortunatly but i dont know why is_dir doesnt work i got no errors nothing nmnor the dir is created
streetparade
@Mike: True, but this way you know which condition (doesn't exist or isn't a directory) led to the false return value.
GreenMatt
i forgot to set mkdir to true like this mkdir($mydir,0655,true);
streetparade
@streetparade: Have you tried running this from the command line? If you're running via the web, have you checked the web server error logs?
GreenMatt
Thanks for the help
streetparade
+1  A: 

Try this:

$dir = "/path/to/dir";
if(is_dir($dir) == false)
    mkdir($dir);

If you want the complete path the be created (if not present), set recusive parameter to true.

See documentation of mkdir for more information.

Veger
You were faster then me. :)
John Conde
+1  A: 

To expand on the answer above based on the questioner's comments:

$filename = "/tmp";
if (!is_dir($filename)) {
    mkdir($filename);
}

You need to use mkdir() to actually make the directory.

John Conde