is_file or file_exists in PHP

Solution 1:

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().

Solution 2:

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.

Solution 3:

Neither.

is_file() returns true if the file can be read.

file_exists() can return true if the file is a directory.

Note that in some edge cases file_exists() returns true when is_file() does not because of permissions or edge case filesystem issues where is_file() cant determine if its a "regular file".

Speed doesn't matter here because they are not the same and they will trade places in speed depending on circumstances.

Solution 4:

I know this post is old but the difference between this functions is not only their behaviours. If you use is_file() to check the existence of big file, more than 2 Go. You will be surprise. File not exists. :( But if you check with file_exists(), that's works.