Check if File Exists in PHP

- 1 minute read

Here’s how you can check if a file on your computer/server exists in PHP:

$file = '/path/to/example.jpg';

$exists = file_exists($file);

In the above example, $exists will return true or false depending on whether there is a file or folder at $file.

However, the following example will only return true if a file is at the specified path:

function fileExists($file) {
    if (is_file($file)) {
        if (file_exists($file)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

Even if a folder is at the specified path, the fileExists function will return false.

Link to this section Conclusion

Please note that you can’t check for files on other sites and servers (including subdomains) with this method. You’ll need to use something like cURL instead.

Thanks for reading!