PHP中is_file不能替代file_exists的理由

yipeiwu_com6年前PHP代码库
我们可以使用下面的代码测试一下:
复制代码 代码如下:
<?php 
      $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根据用户名和手机号查询是否存在手机号码

话不多说,请看代码: public function CheckMobileUser($data){ $sql='select phone,username from wlz...

php多层数组与对象的转换实例代码

多层数组和对象转化的用途很简单,便于处理WebService中多层数组和对象的转化 简单的(array)和(object)只能处理单层的数据,对于多层的数组和对象转换则无能为力。 通过j...

php array_filter除去数组中的空字符元素

除去数组中的空字符元素 复制代码 代码如下: <?php $str1_array=array('【宜配屋www.yipeiwu.com】','','//www.jb51.net',...

Ajax+Jpgraph实现的动态折线图功能示例

Ajax+Jpgraph实现的动态折线图功能示例

本文实例讲述了Ajax+Jpgraph实现的动态折线图功能。分享给大家供大家参考,具体如下: 一 代码 fun.js: var i=1; function progress(){...

php及codeigniter使用session-cookie的方法(详解)

1、读写cookie <1>原生 setcookie('name','value',time) 设置失败,没有正常写入浏览器,测试失败,原因未知 <2>...