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