PHP 檔案系統 stat() 函式



PHP 檔案系統stat()函式用於返回有關檔案的資訊。此函式可以收集名為 filename 的檔案統計資訊。如果 filename 是符號連結,則統計資訊來自檔案本身,而不是符號連結。lstat() 函式類似於 stat() 函式,但它可以基於符號連結的狀態。

語法

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

array stat ( string $filename )

引數

以下是stat()函式唯一必需的引數:

序號 引數及描述
1

$filename(必需)

這是要獲取其資訊的的檔案。

返回值

stat()函式在成功時返回一個包含檔案詳細資訊的陣列,如果出錯則返回 FALSE。

陣列元素

以下是陣列的主要元素:

索引 欄位 描述
[0] dev 裝置號
[1] ino inode 號
[2] mode 檔案模式(保護)
[3] nlink 連結數
[4] uid 所有者的使用者 ID
[5] gid 所有者的組 ID
[6] rdev 裝置型別(如果為 inode 裝置)
[7] size 檔案大小(位元組)
[8] atime 上次訪問時間
[9] mtime 上次修改時間
[10] ctime 上次更改時間
[11] blksize 檔案系統 I/O 的塊大小
[12] blocks 已分配的 512B 塊數

PHP 版本

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

示例

這是一個基本示例,演示如何使用 PHP 檔案系統stat()函式獲取檔案資訊。

<?php
   // Get file stat 
   $stat = stat("/PhpProject/sample.txt");  

   // Print file access time, this is the same as calling fileatime()  
   echo "Acces time: " .$stat["atime"];    

   //Print file modification time, this is the same as calling filemtime()
   echo "\nModification time: " .$stat["mtime"];  
?>

輸出

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

Acces time: 1590217956
Modification time: 1591617832
Device number: 1245376677

示例

這是一個另一個示例,演示如何使用stat()函式處理使用此函式時的錯誤。

<?php
   $stat = stat("/PhpProject/sample.txt");
   
   if(!$stat) {
      echo "stat() call failed...";
   } else {
      $atime = $stat["atime"] + 604800;
   }
   if(!touch("/PhpProject1/sampl2.txt", time(), $atime)) {
      echo "failed to touch file...";
   } else {
      echo "touch() returned success...";
   }
?> 

輸出

這將產生以下結果:

touch() returned success...

示例

這是一個示例,用於檢查提供檔案是否存在,如果存在,則使用stat()函式獲取資訊。

<?php
   $filename = "/PhpProjects/myfile.txt";

   if (file_exists($filename)) {
      $fileinfo = stat($filename);
      echo "File exists!\n";
      echo "File size: " . $fileinfo['size'] . " bytes\n";
      echo "Last modified: " . date('Y-m-d H:i:s', $fileinfo['mtime']) . "\n";
   } else {
      echo "File does not exist.
"; } ?>

輸出

這將生成以下輸出:

File exists!
File size: 74 bytes
Last modified: 2024-06-25 09:08:39

示例

這是一個示例,使用stat()函式獲取檔案資訊,例如檔案大小、上次修改日期和許可權。

<?php
   $filename = "/PhpProjects/myfile.txt";

   // Get file status
   $fileinfo = stat($filename);

   // Display file size in bytes
   echo "File size: " . $fileinfo['size'] . " bytes\n";

   // Display last modified timestamp
   echo "Last modified: " . date('Y-m-d H:i:s', $fileinfo['mtime']) . "\n";

   // Display file permissions
   echo "Permissions: " . decoct($fileinfo['mode'] & 0777) . "\n";
?> 

輸出

這將導致以下輸出:

File size: 74 bytes
Last modified: 2024-06-25 09:08:39
Permissions: 644

總結

stat()方法是一個內建函式,用於以陣列的形式獲取有關給定檔案的資訊。它對於獲取檔案的不同屬性非常有用,例如許可權、大小、修改時間和型別。

php_function_reference.htm
廣告