PHP file_exists() Function
The PHP file_exists() function checks whether a file or directory exists.
Note: The results of this function are cached. Use clearstatcache() function to clear the cache.
Syntax
file_exists(filename)
Parameters
filename |
Required. Specify the path to the file or directory. On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares. |
Return Value
Returns true if the file or directory specified by filename exists. Otherwise returns false.
Exceptions
Upon failure, an E_WARNING is thrown.
Example:
Lets assume that we have a file called test.txt in the current working directory. The example below demonstrates on using this function to check the existence of a file.
<?php $file1 = 'test.txt'; $file2 = 'demo.txt'; //checking the existence of $file1 if(file_exists($file1)) { echo "The file $file1 exists.\n"; } else { echo "The file $file1 does not exist.\n"; } //checking the existence of $file2 if(file_exists($file2)) { echo "The file $file2 exists.\n"; } else { echo "The file $file2 does not exist.\n"; } ?>
The output of the above code will be:
The file test.txt exists. The file demo.txt does not exist.
❮ PHP Filesystem Reference