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
2010-01-22 14:18:48
The call to file_exists(...) is not necessary. is_dir(...) will return false if it does not exist.
Mike
2010-01-22 14:22:51
I would say the same, but he said 'is_dir doesnt work for me'
DaNieL
2010-01-22 14:24:17
`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
2010-01-22 14:25:05
Yeah unfortunatly but i dont know why is_dir doesnt work i got no errors nothing nmnor the dir is created
streetparade
2010-01-22 14:25:15
@Mike: True, but this way you know which condition (doesn't exist or isn't a directory) led to the false return value.
GreenMatt
2010-01-22 14:27:35
i forgot to set mkdir to true like this mkdir($mydir,0655,true);
streetparade
2010-01-22 14:27:53
@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
2010-01-22 14:28:54
Thanks for the help
streetparade
2010-01-22 14:28:49
+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
2010-01-22 14:25:22
+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
2010-01-22 14:26:37