PHP中的is_file或file_exists

Dun*_*oit 113 php file exists

我需要检查文件是否在指定位置的HDD上($ path.$ file_name).

哪个是is_file()file_exists()函数之间的区别,哪个更好/更快在PHP中使用?

hbw*_*hbw 161

is_file()false如果给定路径指向目录,则返回.file_exists()将返回true给出的路径指向一个有效的文件目录.所以这完全取决于你的需求.如果您想具体了解它是否是文件,请使用is_file().否则,请使用file_exists().

  • 刚刚进行了快速测试,它确实解析了符号链接. (37认同)
  • `file_exists()` 本来可以更好地命名为 `path_exists()` (3认同)
  • 据我所知, if_file 也无法用于符号链接,而不仅仅是目录。 (2认同)

Lam*_*amy 35

is_file()是最快的,但最近的基准测试显示file_exists()对我来说稍微快一些.所以我想这取决于服务器.

我的测试基准:

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";
}
Run Code Online (Sandbox Code Playgroud)

编辑:@Tivie感谢您的评论.将周期数从1000改为10k.结果是:

  1. 当文件存在时:

    is_file x 10000 1.5651218891144秒

    file_exists x 10000 1.5016479492188秒

    is_readable x 10000 3.7882499694824秒

  2. 当文件不存在时:

    is_file x 10000 0.23920488357544秒

    file_exists x 10000 0.22103786468506秒

    is_readable x 10000 0.21929788589478秒

编辑:移动clearstatcache(); 在循环内.谢谢CJ丹尼斯.

  • 为什么人们对哪个感兴趣更快,因为这两个函数有不同的行为(如接受的答案中提到的那样,测试它是指向文件的文件还是符号链接(但不是目录而不是符号链接)指向一个目录),另一个测试它是否是一个文件(也可以是一个目录). (7认同)
  • 为了使这个基准工作,你应该添加clearstatcache(); 因为is_file和file_exists的结果在整个脚本中被缓存.无论如何file_exists()有点慢,但除非你执行大约100K文件检查,否则不应该有任何区别.http://www.php.net/manual/en/function.clearstatcache.php (6认同)
  • @Brandin人们很感兴趣,因为在很多情况下,如果您正在检查文件或目录,您已经知道**,因此它是否存在是唯一重要的事情.因此,如果`is_dir()`比`file_exists()`(它没有,btw)快20%,那么如果你只是检查dirs,这可能是一个重要的区别...... (2认同)