PHP fileatime 函数
最后修改于 2025 年 4 月 3 日
PHP 的 fileatime 函数获取文件的最后访问时间。它返回一个 Unix 时间戳,表示文件最后一次被访问的时间。
基本定义
fileatime 函数返回文件最后一次被访问的时间。它接受一个参数:文件名路径,以字符串形式表示。
语法: fileatime(string $filename): int|false。成功时返回 Unix 时间戳,失败时返回 false。需要文件存在并且有权限。
基本的 fileatime 示例
这展示了使用 fileatime 获取访问时间的最简单用法。
basic_fileatime.php
<?php
declare(strict_types=1);
$filename = "example.txt";
$accessTime = fileatime($filename);
if ($accessTime !== false) {
echo "Last accessed: " . date("Y-m-d H:i:s", $accessTime);
} else {
echo "Could not get access time";
}
这获取 "example.txt" 的访问时间并格式化它。如果文件不存在或无法访问,该函数将返回 false。
比较访问时间
我们可以比较两个文件的访问时间,以查看哪个文件最近被访问。
compare_times.php
<?php
declare(strict_types=1);
$file1 = "file1.txt";
$file2 = "file2.txt";
$time1 = fileatime($file1);
$time2 = fileatime($file2);
if ($time1 > $time2) {
echo "$file1 was accessed more recently";
} elseif ($time2 > $time1) {
echo "$file2 was accessed more recently";
} else {
echo "Both files were accessed at the same time";
}
这比较了两个文件的访问时间。请注意,某些文件系统出于性能原因禁用了访问时间记录。
检查最近的访问
我们可以检查一个文件是否在某个时间段内被访问过。
recent_access.php
<?php
declare(strict_types=1);
$filename = "data.log";
$accessTime = fileatime($filename);
$oneDayAgo = time() - 86400; // 24 hours ago
if ($accessTime !== false && $accessTime > $oneDayAgo) {
echo "File was accessed within the last 24 hours";
} else {
echo "File not accessed recently or error occurred";
}
这检查文件是否在过去的 24 小时内被访问过。该示例使用 time() 函数获取当前时间戳进行比较。
处理错误
在使用文件系统函数时,适当的错误处理非常重要。
error_handling.php
<?php
declare(strict_types=1);
$filename = "nonexistent.txt";
$accessTime = fileatime($filename);
if ($accessTime === false) {
if (!file_exists($filename)) {
echo "File does not exist";
} elseif (!is_readable($filename)) {
echo "File is not readable";
} else {
echo "Unknown error getting access time";
}
} else {
echo "Last accessed: " . date("Y-m-d H:i:s", $accessTime);
}
这演示了全面的错误处理。当 fileatime 返回 false 时,我们检查文件是否存在以及是否可读。
与目录一起使用
fileatime 也可以用于目录,而不仅仅是文件。
directory_access.php
<?php
declare(strict_types=1);
$dir = "/var/www/html";
$accessTime = fileatime($dir);
if ($accessTime !== false) {
echo "Directory last accessed: " . date("Y-m-d H:i:s", $accessTime);
echo "<br>";
echo "Days since last access: " . round((time() - $accessTime) / 86400);
} else {
echo "Could not get directory access time";
}
这获取目录的访问时间并计算自上次访问以来的天数。在大多数系统上,目录访问时间的工作方式与文件访问时间类似。
最佳实践
- 性能: 访问时间记录可能被禁用。
- 错误处理: 始终检查 false 返回值。
- 权限: 确保适当的文件权限。
- 时区: 格式化时请注意时区设置。
来源
本教程涵盖了 PHP 的 fileatime 函数,并提供了实际示例,展示了它在不同场景中的用法。
作者
列出 所有 PHP 文件系统函数。