Skip to content
PHP Logo

What potential issues can arise when using file_exists to check if a file already exists in PHP?

When using file_exists to check if a file already exists in PHP, one potential issue is that the function can return true for directories as well as files. To solve this issue, you can use is_file along with file_exists to specifically check if the path is a file.

php
$file_path = 'path/to/file.txt';

if (file_exists($file_path) && is_file($file_path)) {
    // File exists and is a regular file
    echo 'File already exists.';
} else {
    // File does not exist or is not a regular file
    echo 'File does not exist.';
}