我需要检查指定位置($path.$file_name)的硬盘中是否存在一个文件。
is_file()
和 file_exists()
函数有什么区别?在 PHP 中使用哪个更好/更快?
我需要检查指定位置($path.$file_name)的硬盘中是否存在一个文件。
is_file()
和 file_exists()
函数有什么区别?在 PHP 中使用哪个更好/更快?
is_file()
会在给定路径指向一个目录时返回false
。而file_exists()
会在给定路径指向有效的文件或目录时返回true
。因此,完全取决于您的需求。如果您想特别知道它是否是文件,请使用is_file()
。否则,请使用file_exists()
。
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";
}
编辑:@Tivie 感谢您的评论。将循环次数从1000更改为10k。结果如下:
当文件存在时:
is_file x 10000 1.5651218891144 秒
file_exists x 10000 1.5016479492188 秒
is_readable x 10000 3.7882499694824 秒
当文件不存在时:
is_file x 10000 0.23920488357544 秒
file_exists x 10000 0.22103786468506 秒
is_readable x 10000 0.21929788589478 秒
编辑:将 clearstatcache(); 放在循环内部。感谢 CJ Dennis。
is_file()
比file_exists()
更快。如果你知道它是一个文件(而不是目录),一定要使用它。 - Jonathanis_dir()
比 file_exists()
快20%(顺便说一句,它并不是),那么如果你只是检查目录,这可能是一个重要的区别... - Byson都不是。
is_file() 如果可以读取文件,返回 true。
file_exists() 可以在文件为目录时返回 true。
需要注意的是,在某些边缘情况下,由于权限或边缘情况文件系统问题,file_exists() 返回 true 而 is_file() 不返回 true ,因为 is_file() 无法确定它是否为“普通文件”。
这里速度并不重要,因为它们并不相同,根据情况它们的速度会互相交换。
is_file()
什么情况下会返回 true
? - fritzmg我知道这篇文章有点老了,但是这些函数之间的区别不仅在于它们的行为。 如果你使用is_file()来检查大于2GB的文件是否存在,你会感到惊讶。 文件不存在。:( 但是如果你使用file_exists()来检查,就能正常工作。
is_file
如果使用反斜杠: \is_file
,会更快。在这种情况下,PHP 将提供 opcache 优化,而 file_exists
则不会。
file_exists()
could have been better named aspath_exists()
- Jay Dadhania