The reason why is_file cannot replace file_exists in PHP

  • 2021-01-14 05:46:26
  • OfStack

We can test 1 with the following code:
<?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";
      }
?>

When we run the test code, we make sure that the test.txt file exists. In the above code, the first time the is_file function is used to determine whether the file exists, and then the sleep function is called to sleep for 10 seconds. In the next 10 seconds, we'll delete the test.txt file. Finally, look at the result of the second call to the is_file function. The output is as follows:
test.txt exists!
test.txt exists!
Well, you read that right, both times the output was "test.txt exists!" Why is this? The reason is that is_file has a cache. The first time is_file is called, PHP saves the file attributes (file stat). When is_file is called again, if the file name is the same as the first time, it will be returned directly to the cache.
How about is_file instead of file_exists? We can change the function is_file to file_exists in the above code and use the above test method again. The results are as follows:
test.txt exists!
test.txt no exists!
The second call to file_exists does not return the file. This is because the function file_exists does not have a cache. Each call to file_exists will search the disk for the existence of the file, so the second call will return the file.
Having said all that, I just want to say that is_file cannot be used in place of file_exists. If you think is_file is good, then I can't help it

Related articles: