Checking Whether a File Exists

The act of checking whether a file exists is one of the most basic file-related tasks you'll want to do, and file_exists() makes it as easy as it should be. Specify the filename to check as the only parameter, and it returns true if the file exists and false otherwise. For example:

    if (file_exists("snapshot1.png")) {
            print "Snapshot1.png exists!\n";
    } else {
            print "Snapshot1.png does not exist!\n";
    }

Warning

The result of file_exists() is cached, which means you first need to call the clearstatcache() function if you want to be absolutely sure a file exists.

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.