Question

I need to check if a file is on HDD at a specified location ($path.$file_name).

Which is the difference between is_file() and file_exists() functions and which is better/faster to use in PHP?

Was it helpful?

Solution

is_file() will return false if the given path points to a directory. file_exists() will return true if the given path points to a valid file or directory. So it would depend entirely on your needs. If you want to know specifically if it's a file or not, use is_file(). Otherwise, use file_exists().

OTHER TIPS

is_file() is the fastest, but recent benchmark shows that file_exists() is slightly faster for me. So I guess it depends on the server.

My test benchmark:

benchmark('is_file');
benchmark('file_exists');
benchmark('is_readable');

function benchmark($funcName) {
    $numCycles = 10000;
    $time_start = microtime(true);
    for ($i = 0; $i < $numCycles; $i++) {
        clearstatcache();
        $funcName('path/to/file.php'); // or 'path/to/file.php' instead of __FILE__
    }
    $time_end = microtime(true);
    $time = $time_end - $time_start;
    echo "$funcName x $numCycles $time seconds <br>\n";
}

Edit: @Tivie thanks for the comment. Changed number of cycles from 1000 to 10k. The result is:

  1. when the file exists:

    is_file x 10000 1.5651218891144 seconds

    file_exists x 10000 1.5016479492188 seconds

    is_readable x 10000 3.7882499694824 seconds

  2. when the file does not exist:

    is_file x 10000 0.23920488357544 seconds

    file_exists x 10000 0.22103786468506 seconds

    is_readable x 10000 0.21929788589478 seconds

Edit: moved clearstatcache(); inside the loop. Thanks CJ Dennis.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top