The file_exists method check whether a file or directory exists or not. It accepts the path of the file or directory to be checked as the parameter. The following are its uses −
It is useful when you need to know whether a file exists or not before processing.
With that, use this function while creating a new file to know whether the file already exists or not.
Syntax
file_exists($file_path)
Parameters
file_path − Set the path of file or directory to be checked for existence.Required.
Return
The file_exists() method returns.
- True, if the file or directory exists
- False, if the file or directory does not exist
Example
Let us see an example that checks for “candidate.txt” file and display a message even if the file does not exist.
<?php $myfile = '/doc/candidate.txt'; if (file_exists($myfile)) { echo "$myfile exists!"; } else { echo "$myfile does not exist!"; } ?>
The following is the output showing the file does not exist.
Output
/doc/candidate.txt does not exist!