PHP 檔案系統 clearstatcache() 函式



PHP 檔案系統clearstatcache()函式用於清除檔案狀態資料快取。為了提高效率,PHP 會快取特定函式的資料。當指令碼需要準確的結果並多次訪問檔案時,clearstatcache()確保不會使用快取的資料。

此功能在對同一檔案執行多個操作時很有用,因為它只針對這些檔名清除快取資料,確保資料是最新的。

clearstatcache() 函式的必要性

PHP 會快取各種內建函式(如 stat())的結果,以節省資源消耗。即使這種快取提高了效率,如果檔案被修改並且稍後在指令碼中呼叫該函式,資料也可能過時。為了確保檔案更新後的資料有效,需要呼叫clearstatcache()以清除有關檔案狀態的快取資訊。

語法

以下是 PHP 檔案系統clearstatcache()函式的語法:

void clearstatcache ([ bool $clear_realpath_cache = FALSE [, string $filename ]] )

引數

以下是clearstatcache()函式的必填和可選引數:

序號 引數及說明
1

clear_realpath_cache(必填)

一個布林值,指示是否清除 realpath 快取。如果設定為 TRUE,則清除快取。

2

filename(可選)

一個包含要清除其快取的檔名的字串。如果給出快取,則僅刪除該特定檔案的快取。

返回值

該函式返回 NULL。

PHP 版本

clearstatcache()函式最初作為 PHP 4 核心的一部分引入,並且與 PHP 5、PHP 7、PHP 8 相容。

示例

因此,我們將在這個示例中看到 PHP 檔案系統clearstatcache()函式的基本用法。因此,我們將檢查並列印位於“/PhpProject”目錄中的檔案“sample.txt”的檔案大小。

在程式碼中,除了clearstatcache()之外,我們還使用了 filesize()、fopen()、ftruncate() 和 fclose() 函式。這些函式可用於操作和獲取有關檔案“/PhpProject/sample.txt”的資訊,例如其大小。

<?php
   // check filesize
   echo filesize("/PhpProject/sample.txt");
   echo "\n";

   $file = fopen("/PhpProject/sample.txt", "a+");
   // truncate file
   ftruncate($file, 100);
   fclose($file);

   // Clear cache and check filesize again
   clearstatcache();
   echo filesize("/PhpProject/sample.txt"); 
?>

輸出

這將產生以下結果:

25
100

示例

我們還可以使用 PHP 中帶引數的clearstatcache()方法來從快取中刪除特定檔案資訊。

<?php
   $file = "sample.txt";

   // Clears cache for "sample.txt" only
   clearstatcache(true, $file); 
   echo "Cache cleared for $file\n";

   // Clear cache for all files
   clearstatcache(true); 
   echo "Cache cleared for all files\n";

?> 

輸出

這將生成以下結果:

Cache cleared for all files

示例

現在我們將嘗試使用clearstatcache()和 filesize() 函式清除快取。因此,我們將顯示清除快取之前和之後的檔案大小。

<?php
   // File path
   $file = "/Applications/XAMPP/xamppfiles/htdocs/mac/myfile.txt";

   // get filesize before clearing cache
   echo "Filesize before clearing cache: " . filesize($file) . "<br>";

   // clear cache for the specific file
   clearstatcache(true, $file);

   // get filesize after clearing cache
   echo "Filesize after clearing cache: " . filesize($file) . "<br>";
?> 

輸出

這將導致以下結果:

Filesize before clearing cache: 756
Filesize after clearing cache: 305

受影響的函式

PHP 快取這些函式的結果:

stat() lstat() file_exists()
is_writable() is_readable() is_executable()
is_file() is_dir() is_link()
filectime() fileatime() filemtime()
fileinode() filegroup() fileowner()
filesize() filetype() fileperms()

重要說明

  • 當檔案被刪除時,unlink() 函式會自動清除快取,因此無需使用clearstatcache()
  • PHP 在使用 file_exists() 時會快取資訊,但僅針對現有檔案。它不會快取不存在的檔案的資料。
  • 如果您對同一檔名執行多個操作並且需要刪除有關該特定檔案的快取資訊,請使用clearstatcache(),因為它會快取有關特定檔名的資訊。

總結

clearstatcache()函式對於刪除快取的檔案狀態並檢索有關檔案或函式的最新資訊非常有用。它是一個整合的 PHP 檔案系統函式。

php_function_reference.htm
廣告