PHP lstat 函数
最后修改于 2025 年 4 月 3 日
PHP 的 lstat 函数收集有关文件或符号链接的信息。与 stat 不同,它不会跟随符号链接。
基本定义
lstat 函数返回一个包含文件状态信息的数组。它的工作方式类似于 stat,但不会跟随符号链接。
语法:lstat(string $filename): array|false。成功时返回一个数组,失败时返回 false。该数组包含详细的文件统计信息。
基本 lstat 示例
这显示了使用 lstat 获取文件信息的最简单方法。
basic_lstat.php
<?php
declare(strict_types=1);
$file = "example.txt";
$stats = lstat($file);
if ($stats !== false) {
print_r($stats);
} else {
echo "Could not get file stats";
}
这将输出一个包含文件统计信息的数组。该数组包含数字和关联索引,以及各种文件属性,如大小和权限。
检查文件大小
我们可以使用 lstat 获取文件的大小(以字节为单位)。
file_size.php
<?php
declare(strict_types=1);
$file = "example.txt";
$stats = lstat($file);
if ($stats !== false) {
echo "File size: " . $stats['size'] . " bytes";
} else {
echo "Could not get file stats";
}
这使用 stats 数组中的 'size' 索引显示文件大小。无论文件系统如何,大小始终以字节为单位。
检查文件权限
lstat 可用于检查文件权限和类型。
file_permissions.php
<?php
declare(strict_types=1);
$file = "example.txt";
$stats = lstat($file);
if ($stats !== false) {
$permissions = $stats['mode'] & 0777;
echo "Permissions: " . decoct($permissions);
} else {
echo "Could not get file stats";
}
这显示了如何从模式值中提取权限位。我们使用按位与 0777 来仅获取权限位。
检查文件修改时间
我们可以使用 lstat 检查文件上次修改的时间。
modification_time.php
<?php
declare(strict_types=1);
$file = "example.txt";
$stats = lstat($file);
if ($stats !== false) {
$mtime = date("Y-m-d H:i:s", $stats['mtime']);
echo "Last modified: " . $mtime;
} else {
echo "Could not get file stats";
}
这将修改时间戳转换为人类可读的格式。'mtime' 索引包含最后修改的 Unix 时间戳。
检查符号链接
lstat 特别适用于检查符号链接。
symbolic_link.php
<?php
declare(strict_types=1);
$link = "symlink_to_file";
$stats = lstat($link);
if ($stats !== false) {
if (($stats['mode'] & 0xF000) === 0xA000) {
echo "This is a symbolic link";
} else {
echo "This is not a symbolic link";
}
} else {
echo "Could not get file stats";
}
这通过检查模式位来检查文件是否为符号链接。模式中的值 0xA000 表示符号链接。
最佳实践
- 错误处理:始终检查 lstat 是否返回 false。
- 符号链接:当您需要链接信息时,请使用 lstat。
- 性能:如果多次检查,请缓存结果。
- 安全性:在使用之前验证文件名。
来源
本教程涵盖了 PHP lstat 函数,并提供了实际示例,展示了它在不同场景中的用法。
作者
列出 所有 PHP 文件系统函数。