Detailed explanation of the difference between is_file and file_exists in PHP


The first question to ask is, can is_file really be used in place of file_exists? the answer is negative. Why? The reason is simple, is_file has a cache.
We can test it 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 running the test code, we make sure the test.txt file exists. In the above code, the is_file function is used for the first time to determine whether the file exists, and then the sleep function is called to sleep for 10 seconds. During these 10 seconds, we want to 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, the output is "test.txt exists!" twice, why is this? The reason is that is_file has a cache. When the is_file function is called for the first time, PHP will save the file attribute (file stat), and when the is_file is called again, if the file name is changed to the same as the first time, it will directly return to the cache.
So what about changing is_file to file_exists? We can change the is_file function of the above code to the file_exists function, and use the above test method to test again. The results are as follows:
test.txt exists!
test.txt no exists!
The second time file_exists is called, the returned file does not exist. This is because the file_exists function is not cached, and every time file_exists is called, it will go to the disk to search for the existence of the file, so the first It will return false twice.
Having said so much, I just want to explain that is_file cannot be used in place of file_exists. If you insist that is_file has good performance, then I can't do anything about it.

{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324088992&siteId=291194637