PHP 檔案系統 touch() 函式



PHP 檔案系統touch()函式用於設定給定檔案的訪問和修改時間,成功時返回true,失敗時返回false。

請注意,無論引數數量如何,訪問時間總是會被修改。

語法

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

bool touch ( string $filename [, int $mtime = time() [, int $atime ]] )

引數

以下是touch()函式的必需和可選引數:

序號 引數及說明
1

$filename(必填)

這是要修改的檔名。

2

$mtime(可選)

這是修改時間。如果未指定此時間,則使用當前系統時間。

3

$atime(可選)

如果存在,則將指定檔名的訪問時間設定為 atime。否則,將其設定為 time 引數指定的值。如果兩者都不可用,則使用當前系統時間。

返回值

touch()函式成功時返回 TRUE,失敗時返回 FALSE。

變更日誌

在 PHP 8.0.0 版本中,mtime 和 atime 現在可以為空。

PHP 版本

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

示例

這是一個基本示例,演示如何使用 PHP 檔案系統touch()函式設定提供的檔案 sample.txt 的訪問和修改時間。

<?php
   $filename = "/PhpProject/sample.txt";
   if(touch($filename)) {
      echo $filename . " modification time has been changed to present time";
   } else {
      echo "Sorry, could not change modification time of " . $filename;
   }
?>

輸出

以下是以下程式碼的結果:

/PhpProject/sample.txt modification time has been changed to present time

示例

另一個示例演示如何使用touch()函式將檔案的修改時間修改為當前時間前 1 小時。

<?php
   $time = time() - 3600;
   if (!touch("/PhpProject/sample.txt", $time)) {
      echo "oops, something went wrong...";
   } else {
      echo "Touched file with success";
   }
?> 

輸出

這將產生以下結果:

Touched file with success

示例

還有一個示例演示如何使用touch()函式設定給定檔案的特定訪問時間和修改時間。

<?php
   $filename = '/PhpProjects/myfile.txt';
   $timestamp = strtotime('2024-01-01 12:00:00');

   // Set a specific access/modification time for the file
   if (touch($filename, $timestamp)) {
      echo "File '$filename' access/modification time set to " . date('Y-m-d H:i:s', $timestamp);
   } else {
      echo "Failed to set access/modification time for file '$filename'.";
   }
?> 

輸出

這將生成以下輸出:

File '/PhpProjects/myfile.txt' access/modification time set to 2024-01-01 12:00:00

示例

現在假設給定的檔案不存在,那麼touch()函式如何處理這種情況呢?讓我們看看。

<?php
   $filename = '/PHP/PhpProjects/abc.txt';

   // Try to change the access/modification time of a file that is not present
   if (touch($filename)) {
      echo "File '$filename' access/modification time updated.";
   } else {
      echo "Failed to update file '$filename': \n" . error_get_last()['message'];
   }
?> 

輸出

這將導致以下輸出:

Failed to update file '/PHP/PhpProjects/abc.txt': touch(): 
Unable to create file /PHP/PhpProjects/abc.txt because No such file or directory

總結

touch()方法是一個內建函式,用於設定給定檔案的訪問或修改時間。如果檔案不存在,此函式會先建立檔案。

php_function_reference.htm
廣告