Check if a File Exists in PHP Using file_exists
When working with files in PHP, attempting to read a non-existent
file will trigger warnings and potentially disrupt your application’s
flow. This article explains how to safely verify a file’s existence on
your server using the native PHP file_exists() function
before executing any read operations.
Understanding the file_exists() Function
The file_exists() function is a built-in PHP function
that checks whether a specified file or directory exists on the server.
It accepts a single string parameter representing the file path and
returns true if the file or directory exists, and
false if it does not.
Basic Syntax and Implementation
To safely read a file, you should wrap your file-reading logic (such
as file_get_contents() or fopen()) inside a
conditional if statement that checks the output of
file_exists().
Here is the standard implementation:
<?php
// Define the path to the file
$filePath = 'uploads/document.txt';
// Check if the file exists before reading
if (file_exists($filePath)) {
// Read and output the file contents
$fileContent = file_get_contents($filePath);
echo $fileContent;
} else {
// Handle the error gracefully
echo "Error: The requested file does not exist on the server.";
}
?>Best Practices: file_exists() vs. is_file()
While file_exists() checks for both files and
directories, you may sometimes want to ensure that the target path is
specifically a file and not a folder. In such cases, combine it with
is_file() or use is_file() directly, as it
also returns false if the file does not exist.
<?php
$filePath = 'uploads/document.txt';
if (file_exists($filePath) && is_file($filePath)) {
// Safe to read the file
$fileContent = file_get_contents($filePath);
echo $fileContent;
}
?>Important Considerations
- Caching: PHP caches the results of file status
functions like
file_exists()for performance reasons. If a file is being created or deleted repeatedly during the same script execution, callclearstatcache()to clear the cache and get accurate results. - Permissions: If the parent directories do not have
the correct read permissions for the PHP system user,
file_exists()will returnfalseeven if the file physically exists on the server.