How to Check if File Exists in PHP: Simple Guide
In PHP, you can check if a file exists using the
file_exists() function by passing the file path as a string. It returns true if the file is found and false if not.Syntax
The file_exists() function checks whether a file or directory exists at the specified path.
- Parameter: A string representing the path to the file or directory.
- Return: Boolean
trueif the file/directory exists, otherwisefalse.
php
bool file_exists(string $filename)
Example
This example shows how to check if a file named example.txt exists in the current directory and prints a message accordingly.
php
<?php $filename = 'example.txt'; if (file_exists($filename)) { echo "File '$filename' exists."; } else { echo "File '$filename' does not exist."; } ?>
Output
File 'example.txt' exists.
Common Pitfalls
Common mistakes when using file_exists() include:
- Using incorrect file paths or relative paths that do not point to the intended location.
- Not having proper permissions to access the file, which can cause unexpected
falseresults. - Confusing
file_exists()with functions that check if a file is readable or writable.
Always verify the path and permissions before relying on file_exists().
php
<?php // Wrong: Using wrong path if (file_exists('wrong/path/example.txt')) { echo "File exists."; } else { echo "File does not exist."; } // Right: Use correct path if (file_exists(__DIR__ . '/example.txt')) { echo "File exists."; } else { echo "File does not exist."; } ?>
Output
File does not exist.File exists.
Quick Reference
Remember these tips when checking if a file exists in PHP:
- Use
file_exists()for existence check only. - Use absolute paths or reliable relative paths.
- Check file permissions if results are unexpected.
- For checking if a file is readable or writable, use
is_readable()oris_writable().
Key Takeaways
Use file_exists() with the file path to check if a file exists in PHP.
file_exists() returns true if the file or directory exists, false otherwise.
Always verify the file path and permissions to avoid false negatives.
Use absolute paths or __DIR__ for reliable file location.
file_exists() only checks existence, not readability or writability.