PHP中is_file不能替代file_exists的理由_PHP教程

來源:互聯網
上載者:User
我們可以使用下面的代碼測試一下:
複製代碼 代碼如下: $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的效能好,那我也沒辦法

http://www.bkjia.com/PHPjc/736811.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/736811.htmlTechArticle我們可以使用下面的代碼測試一下: 複製代碼 代碼如下: ?php $filename = 'test.txt'; if (is_file($filename)) { echo "$filename exists!\n"; } else { echo "$filena...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.