PHP is_file与file_exists用法分析
在php编程中,is_file真的可以替代file_exists使用吗?答案是否定的。
原因很简单:is_file有缓存
测试代码:
$filename = 'test.txt';
if (is_file($filename)) {
echo "$filename exists!\n";
} else {
echo "$filename no exists!\n";
}
sleep(10);
if (is_file($filename)) {
echo "$filename exists!\n";
} else {
echo "$filename no exists!\n";
}
?>
在运行测试代码时,我们确保test.txt文件存在。在上面的代码中,第一次使用is_file函数判断文件是否存在,然后调用sleep函数睡眠10秒。在这10秒内,我们要把test.txt文件删除。最后看看第二次调用is_file函数的结果。输出结果如下:
test.txt exists!
test.txt exists!
嗯,你没有看错,两次都是输出“test.txt exists!”,这是为什么呢?原因就是is_file有缓存。第一次调用is_file函数的时候,PHP会把文件的属性(file stat)保存下来,当再次调用is_file的时候,如果文件名更第一次的一样,那么就会直接返回缓存。
那么把is_file改为file_exists呢?我们可以把上面代码的is_file函数改为file_exists函数,再次使用上面的测试方法测试。结果如下:
test.txt exists!
test.txt no exists!
第二次调用file_exists的时候返回文件不存在,这是因为file_exists函数没有缓存,没次调用file_exists的时候都会去磁盘搜索文件是否存在,所以第二次才会返回false。
说了那么多,我只想说明is_file不能代替file_exists使用,如果你硬是觉得is_file的性能好,那我也没办法。
您可能感兴趣的文章:
PHP is_file与file_exists用法分析
php file_exists is_file与is_dir函数的区别分析
php 判断文件存在与否的函数选择(file_exists or is_file)
PHP is_file、file_exists、is_dir总结
php中is_file与file_exists的区别
PHP中file_exists与is_file,is_dir的区别
file_exists与is_file、is_dir的区别
php判断是否为文件(is_file())或目录(is_dir())的实例代码
php判断文件是否存在file_exists 与 is_file详解
php中is_file和file_exists与is_dir的区别