is_file or file_exists in PHP

旧时模样 提交于 2019-11-28 19:24:58

问题


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?


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




回答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.



来源:https://stackoverflow.com/questions/792899/is-file-or-file-exists-in-php

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