PHP 提供一組標準函式取得檔案系統中繼資料:filesize()、fileatime()、filemtime()、filectime(),搭配 date() 格式化即可人類可讀顯示。
| 函式 | 意義 | 回傳值 | 備註 |
|---|---|---|---|
| filesize($file) | 檔案大小 | 位元組數 (int) | 大於 2GB 需 64 位系統 |
| fileatime($file) | 最後存取時間 | Unix 時間戳 | 讀取、執行會更新 |
| filemtime($file) | 最後內容修改時間 | Unix 時間戳 | 寫入、truncate 會更新 |
| filectime($file) | 最後狀態變更時間 | Unix 時間戳 | chmod、chown、rename、移動會更新 |
| fileperms($file) | 權限位元遮罩 | int | 配合 decoct() 顯示八進位 |
| fileowner($file) | 擁有者 UID | int | 需權限 |
| filegroup($file) | 群組 GID | int | 需權限 |
<?php
$file = 'samplefile.doc';
if (!file_exists($file)) {
die("檔案不存在: $file");
}
echo "檔案大小: " . filesize($file) . " bytes\n";
echo "最後存取: " . date('Y-m-d H:i:s', fileatime($file)) . "\n";
echo "最後修改: " . date('Y-m-d H:i:s', filemtime($file)) . "\n";
echo "狀態變更: " . date('Y-m-d H:i:s', filectime($file)) . "\n";
echo "權限: " . decoct(fileperms($file) & 0777) . "\n";
// 進階:SplFileInfo 物件導向介面
$info = new SplFileInfo($file);
echo "副檔名: " . $info->getExtension() . "\n";
echo "基礎名稱: " . $info->getBasename() . "\n";
echo "是否可讀: " . ($info->isReadable() ? '是' : '否') . "\n";
echo "是否可寫: " . ($info->isWritable() ? '是' : '否') . "\n";
?>
stat() 系統呼叫結果(clearstatcache() 清除)。clearstatcache(true, $file)(PHP 5.3+ 支援指定路徑清除)。fileatime 可能不準確(預設關閉 last access 更新),可透過 fsutil behavior set disablelastaccess 0 啟用。filemtime)。filectime/filemtime)。filectime 變更偵測)。掌握檔案中繼資料操作,是 PHP 檔案系統程式設計的基石技能。