The file_exists()
function in PHP is used to check whether a file or directory exists. It returns true
if the file or directory exists, and false
otherwise.
Syntax:
file_exists(string $filename): bool
- $filename: The path to the file or directory.
Example 1: Checking if a file exists
<?php
$file = 'example.txt';
if (file_exists($file)) {
echo "The file '$file' exists.";
} else {
echo "The file '$file' does not exist.";
}
?>
Output:
The file 'example.txt' exists.
Example 2: Checking if a directory exists
<?php
$directory = 'images/';
if (file_exists($directory)) {
echo "The directory '$directory' exists.";
} else {
echo "The directory '$directory' does not exist.";
}
?>
Output:
The directory 'images/' exists.
Example 3: Using with a non-existent file
<?php
$file = 'nonexistent.txt';
if (file_exists($file)) {
echo "The file '$file' exists.";
} else {
echo "The file '$file' does not exist.";
}
?>
Output:
The file 'nonexistent.txt' does not exist.
Important Notes:
file_exists()
can check for both files and directories.
- It returns
false
for symlinks pointing to a non-existent target.
- Ensure that the script has the correct file permissions to check the file or directory existence.
This function is commonly used for validating the existence of a file before performing further operations like reading or writing to it.