is_file or file_exists in PHP

筅森魡賤 提交于 2019-11-29 22:43:50

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

Lamy

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!