PHP 檔案系統 fileatime() 函式



PHP 檔案系統fileatime()函式用於返回指定檔案的上次訪問時間。此函式的結果已被快取。我們可以使用clearstatcache()函式清除快取。

每當讀取檔案時,檔案的訪問時間都會發生變化。某些Unix系統會關閉訪問時間更新,因為更新它們會降低效能,尤其是在頻繁訪問許多檔案時。關閉這些更新可以提高效能。

語法

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

int fileatime ( string $filename )

引數

下面提到了使用fileatime()函式所需的引數:

序號 引數及說明
1

filename(必需)

這是檔案路徑。

返回值

返回檔案上次訪問的時間,如果失敗則返回 FALSE。時間將以 Unix 時間戳的形式給出。

PHP 版本

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

示例

這段PHP程式碼使用PHP檔案系統fileatime()函式檢查並顯示檔案的上次訪問時間。以下是此示例的簡單演示:

<?php
   echo fileatime("/PhpProject/sample.txt");
   echo "<br>";
   echo "Last access: ".date("F d Y H:i:s.",fileatime("/PhpProject/sample.txt"));
?>

輸出

這將生成以下結果:

1590217956
Last access: May 23 2020 09:12:36.

示例

這段PHP程式碼檢查檔案是否存在,如果存在,則使用fileatime()函式顯示其上次訪問的時間。以下是此示例的簡單演示:

<?php
   $filename = "/PhpProject/sample.txt";
   if(file_exists($filename)) {
      echo "$filename was last accessed at: " . date("F d Y H:i:s.", fileatime($filename));
   }
?>

輸出

這將產生以下結果:

/PhpProject/sample.txt was last accessed at: May 23 2020 09:12:36.

示例

此PHP示例向我們展示瞭如何檢查陣列中列出檔案的上次訪問時間。它迴圈遍歷每個檔案,檢查它是否存在,如果存在則使用fileatime()函式列印上次訪問時間。

<?php
   // Make an array of file paths
   $files = ["/PhpProject/sample.txt", "/PhpProject/myfile.txt", "/PhpProject/my.php"];

   // Loop over the array of files
   foreach ($files as $file) {
      if (file_exists($file)) {
         echo "$file was last accessed at: " . date("F d Y H:i:s.", fileatime($file)) . "
"; } else { echo "$file does not exist.<br>"; } } ?>

輸出

這將產生以下結果:

/PhpProject/sample.txt was last accessed at: May 30 2024 12:44:57.
/PhpProject/myfile.txt was last accessed at: May 30 2024 12:21:33.
/PhpProject/my.php was last accessed at: May 29 2024 11:47:25.

示例

在下面的PHP程式碼中,我們將比較兩個檔案的訪問時間,使用fileatime()函式並相應地列印訊息。

<?php
   $file1 = "/PhpProject/sample.txt";
   $file2 = "/PhpProject/myfile.txt";

   if (file_exists($file1) && file_exists($file2)) {
      $time1 = fileatime($file1);
      $time2 = fileatime($file2);
      
      if ($time1 > $time2) {
         echo "$file1 was accessed recently than $file2.<br>";
      } elseif ($time1 < $time2) {
         echo "$file2 was accessed recently than $file1.<br>";
      } else {
         echo "$file1 and $file2 were accessed at the same time.<br>";
      }
   } else {
      echo "One or both files do not exist.<br>";
   }
?> 

輸出

這將導致以下結果:

/PhpProject/sample.txt was accessed recently than /PhpProject/myfile.txt.

注意

fileatime()函式可用於儲存檔案的訪問時間;但是,應注意在頻繁的訪問時間更新會影響效能的系統上存在效能問題。

總結

本章我們瞭解了fileatime()函式是什麼,以及fileatime()的一些有用示例。

php_function_reference.htm
廣告