Home > Backend Development > PHP Tutorial > Reasons why the is_file() function cannot replace the file_exists() function

Reasons why the is_file() function cannot replace the file_exists() function

怪我咯
Release: 2023-03-13 14:00:02
Original
2284 people have browsed it

Can

is_file really be used instead of file_exists? the answer is negative. Why? The reason is very simple, is_file has cache

We can use the following code to test it:

The code is as follows:

<?php  
      $filename = &#39;test.txt&#39;;
      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";
      }
?>
Copy after login

Running the test When coding, we make sure the test.txt file exists. In the above code, the is_filefunction is used for the first time to determine whether the file exists, and then the sleep function is called to sleep for 10 seconds. Within these 10 seconds, we will delete the test.txt file. Finally, look at the result of calling the is_file function for the second time. The output results are as follows:
test.txt exists!
test.txt exists!
Well, you read that right, "test.txt exists!" was output twice. Why is this? The reason is that is_file has cache. When the is_file function is called for the first time, PHP will save the attributes (file stat) of the file. When is_file is called again, if the file name is the same as the first time, it will be returned directly. cache.
So what about changing is_file to file_exists? We can change the is_file function in the above code to the file_exists function and use the above test method again to test. The results are as follows:
test.txt exists!
test.txt no exists!
When file_exists is called for the second time, it is returned that the file does not exist. This is because the file_exists function is not cached and will happen every time file_exists is called. Go to disk to search whether the file exists, so it will return false only the second time.
So is_file cannot be used instead of file_exists

The above is the detailed content of Reasons why the is_file() function cannot replace the file_exists() function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template