we want to create a directory if it does not exist. Is just using the is_dir function ok for that purpose? For example:
[pastacode lang=”php” manual=”if%20(!is_dir(%24dir))%20%0A%7B%0A%20%20%20%20mkdir(%24dir)%3B%20%20%20%20%20%20%20%20%20%0A%7D%0AOr%20should%20I%20also%20use%20file_exists%3F%20For%20example%3A%0A%0Aif%20(!file_exists(%24dir)%20%26%26%20!is_dir(%24dir))%20%0A%7B%0A%20%20%20%20mkdir(%24dir)%3B%20%20%20%20%20%20%20%20%20%0A%7D%20%0A” message=”php code” highlight=”” provider=”manual”/]- 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:
[pastacode lang=”javascript” manual=”%24year%20%3D%20date(%22Y%22)%3B%20%20%20%0A%24month%20%3D%20date(%22m%22)%3B%20%20%20%0A%24filename%20%3D%20%22..%2F%22.%24year%3B%20%20%20%0A%24filename2%20%3D%20%22..%2F%22.%24year.%22%2F%22.%24month%3B%0A%0Aif(file_exists(%24filename))%0A%7B%0A%20%20%20%20if(file_exists(%24filename2)%3D%3Dfalse)%0A%7B%0A%20%20%20%20%20%20%20%20mkdir(%24filename2%2C0777)%3B%0A%20%20%20%20%7D%0A%7D%0Aelse%0A%7B%0A%20%20%20%20mkdir(%24filename%2C0777)%3B%0A%7D%0A” message=”javascript code” highlight=”” provider=”manual”/]- 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