Sometimes you may need to write a script where you may need to create a file or directory through PHP. But, you cannot simply create a file or directory just like that, you have to check if the file or folder that you are going to create is already exist or not. This is important because any file or folder should not be overwritten.
Here I have listed down the usage example,
Use ‘file_exists()‘ to check if a file is already present or not. NOTE: This function also can be used to check directory existence.
1 2 3 4 5 6 7 8 9 10 11 |
<?php //check image file if (file_exists("yourfile.jpg")){ echo "Yes, file exist"; } //you can also specify the file path and check if (file_exists("myfolder/yourfile.jpg")){ echo "Yes, file exist"; } ?> |
Use ‘is_dir()‘ to check if a directory is already present or not.
Example 2: Check a Folder (directory) exists or not
1 2 3 4 5 6 |
<?php //check image file if (is_dir("yourfolder")){ echo "Yes, folder exist"; } ?> |
Now, we got to know how to check a file or folder exists. But there will be a chance where is_dir() will not work in some servers. To avoid that, here is the solution, just use both the functions.
1 2 3 4 5 6 7 8 |
<?php $dir = 'yourdirectory'; if (file_exists($dir) and is_dir($dir)) { echo "yes the folder exist"; } ?> |
The above method is very good and will work in all the servers for eg., Unix or Windows