PHP file_exists() Function
Quick summary: The PHP file_exists() function checks whether a file or directory exists.
PHP file_exists() Syntax
file_exists(string $filename): bool
PHP
PHP file_exists() Basic examples
var_dump(file_exists('config.php'));
PHP
Output:
bool(true)
Checks if a path exists.
PHP file_exists() Real-world usage
if (!file_exists('cache.json')) {
file_put_contents('cache.json', '{}');
}
PHP
Output:
int(2)
Creates a file if it does not exist.
PHP file_exists() Edge cases
var_dump(file_exists('missing.txt'));
PHP
Output:
bool(false)
Returns false for missing paths.
PHP file_exists() Common mistakes
Using file_exists for permissions
Existence does not guarantee readability or writability.
Incorrect
file_exists('file.txt');
Correct
is_readable('file.txt');
Check permissions explicitly.
PHP file_exists() Frequently Asked Questions
What does file_exists() do?
Checks if a file or directory exists.
Return type?
Boolean.
Use case?
Checking file presence.
Does it modify file?
No.
Handles directories?
Yes.
Performance?
Fast.
Common mistake?
Race conditions.
Can return false negative?
Yes in rare cases.
Alternative?
is_file or is_dir.
Works with remote URLs?
Not reliably.
Safe?
Yes.
Best practice?
Check before file operations.