filemtime(string $filename): int|false
false<?php
$file = 'test.txt';
$timestamp = filemtime($file);
if ($timestamp !== false) {
echo "原始時間戳: $timestamp\n";
echo "格式化時間: " . date('Y-m-d H:i:s', $timestamp) . "\n";
// 輸出示例:
// 原始時間戳: 1704720000
// 格式化時間: 2024-01-08 14:30:00
} else {
echo "文件不存在或無權限";
}
PHP 為提升性能會緩存 stat() 系統調用結果(包含 filemtime、filesize、is_file 等)。
<?php
$file = 'cache.txt';
echo filemtime($file); // 1704720000
// 外部程序修改了文件
// sleep(1); touch($file); // 模擬修改
echo filemtime($file); // 可能仍返回 1704720000(舊緩存)
// 必須清除緩存
clearstatcache();
echo filemtime($file); // 返回新時間戳
最佳實踐:在同一腳本多次檢查同一文件時,調用 clearstatcache(true, $filename)(PHP 5.3+ 支持針對特定文件清除)。
| 函數 | 含義 | 典型用途 |
|---|---|---|
filemtime | 內容修改時間 | 緩存失效判斷、版本號生成 |
fileatime | 最後訪問時間 | 文件熱度分析(多文件系統默認關閉) |
filectime | inode 變更時間(權限、所有者、重命名、移動) | 安全審計、同步工具 |
<?php
$dir = '/var/www/html';
echo "目錄修改時間: " . date('Y-m-d H:i:s', filemtime($dir));
// 注意:目錄修改時間指「目錄項增減」(文件創建/刪除/重命名),不包含子文件內容修改
<?php
function assetVersion(string $path): string
{
$fullPath = $_SERVER['DOCUMENT_ROOT'] . $path;
$mtime = @filemtime($fullPath);
return $mtime ? "{$path}?v={$mtime}" : $path;
}
// 模板中使用
//
// 輸出: /css/app.css?v=1704720000
// 文件修改後自動更新版本號,瀏覽器強制重新下載
<?php
function getCachedData(string $cacheFile, int $ttl = 3600): mixed
{
if (!is_file($cacheFile)) return null;
// 檢查是否過期
if (time() - filemtime($cacheFile) > $ttl) {
@unlink($cacheFile); // 刪除過期緩存
return null;
}
return unserialize(file_get_contents($cacheFile));
}
function setCachedData(string $cacheFile, mixed $data): void
{
@file_put_contents($cacheFile, serialize($data));
}
<?php
// 開發環境熱重載示例
$configFile = 'config.php';
$lastMtime = 0;
while (true) {
$currentMtime = filemtime($configFile);
if ($currentMtime > $lastMtime) {
echo "配置文件已變更,重新載入...\n";
clearstatcache(true, $configFile);
$config = require $configFile;
$lastMtime = $currentMtime;
// 觸發業務重載邏輯
}
sleep(1);
}
<?php
// 簡易增量部署
$source = '/project/src';
$target = '/var/www/html';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source));
foreach ($iterator as $file) {
if ($file->isFile()) {
$relPath = substr($file->getPathname(), strlen($source) + 1);
$targetFile = $target . '/' . $relPath;
$sourceMtime = $file->getMTime();
$targetMtime = @filemtime($targetFile);
if ($targetMtime === false || $sourceMtime > $targetMtime) {
@mkdir(dirname($targetFile), 0755, true);
copy($file->getPathname(), $targetFile);
echo "已更新: $relPath\n";
}
}
}
false 而非 0 表示失敗,嚴格類型需用 === false 判斷。SplFileInfo::getMTime() 避免重複路徑解析。inotify 擴展實現事件驅動而非輪詢。filemtime 結果到 Redis/APCu,減少系統調用。filemtime() 是文件系統操作的基石,理解其緩存機制與三時間區別,能讓你構建出可靠的緩存失效、版本控制、熱重載與部署自動化系統。