PHP 檔案系統 filemtime() 函式



PHP 檔案系統filemtime()函式用於返回檔案內容上次修改的時間。基本上,它在成功時返回最後修改時間的 Unix 時間戳,失敗時返回 false。

此函式可以返回寫入檔案資料塊的時間,也就是檔案內容發生更改的時間。

語法

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

int filemtime ( string $filename )

引數

以下是此函式的引數:

序號 引數及說明
1

filename(必需)

將要掃描的檔案。

返回值

該函式在成功時返回檔案的最後修改時間(Unix 時間戳),如果檔案不存在或發生錯誤,則返回 FALSE。

PHP 版本

filemtime()函式最初作為核心 PHP 4 的一部分引入,並能很好地與 PHP 5、PHP 7、PHP 8 一起使用。

示例

在下面的示例程式碼中,我們將使用 PHP 檔案系統filemtime()函式獲取函式中提到的檔案的最後修改時間和日期。

由於此函式將最近的修改時間檢索為 Unix 時間戳,因此我們將將其轉換為易於閱讀的日期和時間字串。

<?php
   echo filemtime("/PhpProject/sample.txt"); 
   echo "\n";
   echo "Last modified: ".date("F d Y H:i:s.",filemtime("/PhpProject/sample.txt"));
?>

輸出

這將導致以下結果:

1590392449
Last modified: May 25 2020 09:40:49.

示例

此示例向我們展示瞭如何使用filemtime()函式透過將其修改時間與當前時間進行比較來檢查檔案的“年齡”。

<?php
   // Get the modification time of the file (replace the file path with your file)
   $modTime = filemtime("/Applications/XAMPP/xamppfiles/htdocs/mac/myfile.txt");

   // Get the current time
   $currentTime = time();

   // Get the age of the file in seconds
   $fileAge = $currentTime - $modTime;

   // change seconds to days
   $fileAgeInDays = floor($fileAge / (60 * 60 * 24));

   // echo the age of the file
   echo "File age: $fileAgeInDays days";
?> 

輸出

這將產生以下結果:

File age: 3 days

示例

此示例向我們展示瞭如何使用filemtime()函式透過將修改時間戳附加到檔名來獲取檔案版本。

藉助 rename() 函式,舊檔案將重新命名為包含修改時間戳的新檔名。

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

   //Get the modification time
   $modTime = filemtime($filename);

   // Append modification timestamp to filename
   $newFilename = basename($filename, ".txt") . "_v$modTime.txt";

   // Rename the file
   rename($filename, $newFilename);

   echo "File renamed to: $newFilename";
?> 

輸出

這將生成以下結果:

File renamed to: myfile_v1716886151.txt

示例

此示例展示瞭如何簡單地比較檔案的修改時間以確保沒有任何更改。因此,我們將使用迴圈來比較初始修改時間和當前修改時間。

如果修改時間發生變化,則迴圈結束,並列印顯示“檔案已修改!”的訊息。

<?php
   // Define the file path 
   $filename = "/Applications/XAMPP/xamppfiles/htdocs/mac/myfile.txt";
   
   $initialModTime = filemtime($filename);
   
   while (true) {
      // Clear the file status cache
      clearstatcache(); 
      $currentModTime = filemtime($filename);
   
      if ($currentModTime != $initialModTime) {
            echo "File has been modified!";
            break;
      }
   
      // Wait for 5 seconds before checking again
      sleep(5); 
   }
?> 

輸出

這將產生以下結果:

File has been modified!

注意

因為它在失敗時返回 false,所以它經常用於 if 語句或三元運算子等條件表示式中進行錯誤處理。

總結

filemtime()對於 PHP 開發人員處理檔案操作是一個有用的工具,無論他們是用它進行版本檢查、基本檢查、檔案年齡還是監控。

php_function_reference.htm
廣告