we want to create a directory if it does not exist. Is just using the is_dir function ok for that purpose? For example:
- Both would return true on Unix systems – in Unix everything is a file, including directories. But to test if that name is taken, you should check both.
- There might be a regular file named ‘foo’, which would prevent you from creating a directory name ‘foo’.
- In this scenario, we want to create a folder called “images”:
An explanation of the PHP code snippet above:
- We set the name of the directory that we want to create. In this case, it is “images”.
- We used PHP’s is_dir function to check if the folder already exists. If the is_dir function returns a boolean FALSE value, then we know that the directory in question doesn’t already exist.
- If the directory doesn’t already exist, we can create it using the mkdir function.
Note :that if you fail to check for the directory’s existence, you run the risk of getting a nasty PHP warning:
- If you already have file with the same name, but it is not a directory, !file_exists($dir) will return false, folder will not be created, so error “failed to open stream: No such file or directory” will be occured.
- In Windows there is a difference between ‘file’ and ‘folder’ types, so need to use file_exists() and is_dir() at the same time, for ex.:
Sample code:
- 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:
Great