Checking whether a file exists

bool file_exists ( string filename)

The act of checking whether a file exists is one of the most basic file-related tasks you'll want to do, and thankfully file_exists() makes it as easy as it should be. In fact, it's so easy you should be able to guess the parameter list and return value!

Still here? Oh, alright then - you specify the filename to check as the only parameter, and it returns true if the file exists and false otherwise. Example:

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

Although you're only part-way through this book, I hope you managed to guess how it worked yourself!

Author's Note: 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.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Retrieving a file's status >>

Previous chapter: Other file functions

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.