PHP filemtime 函数
最后修改于 2025 年 4 月 3 日
PHP 的 filemtime 函数以 Unix 时间戳格式返回文件的最后修改时间。它对于缓存、文件同步和版本控制非常有用。
基本定义
filemtime 函数检索文件内容最后修改的时间。它返回一个 Unix 时间戳(自 Unix 纪元以来的秒数)。
语法:filemtime(string $filename): int|false。失败时返回 false。时间戳可以使用 date 函数进行格式化以供显示。
基本 filemtime 示例
这显示了 filemtime 获取修改时间的最简单用法。
basic_filemtime.php
<?php
declare(strict_types=1);
$file = "example.txt";
$timestamp = filemtime($file);
if ($timestamp !== false) {
echo "Last modified: " . date("Y-m-d H:i:s", $timestamp);
} else {
echo "Could not get modification time";
}
这会获取 "example.txt" 的修改时间并将其格式化以供显示。严格类型声明确保了函数返回值处理中的类型安全。
访问前检查文件
在调用 filemtime 之前,请务必验证文件是否存在且可读。
check_file.php
<?php
declare(strict_types=1);
$file = "config.ini";
if (file_exists($file) && is_readable($file)) {
$timestamp = filemtime($file);
echo "Last modified: " . date("F d Y H:i:s", $timestamp);
} else {
echo "File not accessible";
}
此示例演示了在尝试获取文件修改时间之前进行正确的ファイル检查。它可防止警告并优雅地处理错误。
缓存控制示例
filemtime 通常用于 Web 应用程序中的缓存验证。
cache_control.php
<?php
declare(strict_types=1);
$cssFile = "styles.css";
$lastModified = filemtime($cssFile);
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $lastModified) . " GMT");
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified) {
header("HTTP/1.1 304 Not Modified");
exit;
}
这会根据文件修改时间发送正确的缓存头。浏览器可以使用此功能避免重新下载未更改的文件,从而提高性能。
比较文件时间
比较修改时间以确定哪个文件更新。
compare_files.php
<?php
declare(strict_types=1);
$file1 = "data.json";
$file2 = "backup.json";
$time1 = filemtime($file1);
$time2 = filemtime($file2);
if ($time1 > $time2) {
echo "$file1 is newer than $file2";
} elseif ($time1 < $time2) {
echo "$file2 is newer than $file1";
} else {
echo "Files were modified at the same time";
}
此示例比较两个文件的修改时间以确定哪个文件更新。对于同步任务或确定使用哪个版本很有用。
目录修改检查
通过检查目录中的每个文件来检查文件何时被最后修改。
directory_check.php
<?php
declare(strict_types=1);
$dir = "uploads/";
$latestTime = 0;
if (is_dir($dir)) {
foreach (scandir($dir) as $file) {
if ($file !== "." && $file !== "..") {
$fileTime = filemtime($dir . $file);
if ($fileTime > $latestTime) {
$latestTime = $fileTime;
}
}
}
}
echo "Newest file modified: " . date("Y-m-d H:i:s", $latestTime);
这会扫描目录以查找最近修改的文件。对于监控目录更改或查找最新上传的文件很有用。
最佳实践
- 错误处理: 始终检查 filemtime 是否返回 false。
- 文件权限: 确保脚本对文件具有读取访问权限。
- 缓存: 考虑缓存经常检查的文件的结果。
- 时区: 格式化时请注意时区设置。
来源
本教程通过各种场景的实际示例,介绍了 PHP 的 filemtime 函数。
作者
列出 所有 PHP 文件系统函数。