PHP filesize 函数
最后修改于 2025 年 4 月 3 日
PHP 的 filesize 函数以字节为单位返回文件的大小。它在处理或显示文件之前检查文件大小非常有用。
基本定义
filesize 函数返回指定文件的大小。它接受一个参数:文件名或文件的路径。
语法:filesize(string $filename): int|false。成功时返回文件大小(字节),失败时返回 false。结果会被缓存;使用 clearstatcache() 获取最新结果。
基本的 filesize 示例
这展示了 filesize 获取文件大小的最简单用法。
basic_filesize.php
<?php declare(strict_types=1); $filename = "example.txt"; $size = filesize($filename); echo "File size: $size bytes"; // Outputs size in bytes
这以字节为单位获取“example.txt”的大小。该函数需要文件存在且可访问才能正常工作。
格式化文件大小
我们可以将原始字节数格式化为人类可读的格式。
format_size.php
<?php
declare(strict_types=1);
function formatSize(int $bytes): string {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$index = 0;
while ($bytes >= 1024 && $index < 4) {
$bytes /= 1024;
$index++;
}
return round($bytes, 2) . ' ' . $units[$index];
}
$filename = "largefile.zip";
$size = filesize($filename);
echo "File size: " . formatSize($size);
这会将字节转换为适当的单位(KB、MB 等)。该函数通过动态选择最佳单位来处理任何大小的文件。
检查文件是否存在
在获取文件大小之前检查文件是否存在是一个好习惯。
check_existence.php
<?php
declare(strict_types=1);
$filename = "nonexistent.txt";
if (file_exists($filename)) {
$size = filesize($filename);
echo "File size: $size bytes";
} else {
echo "File does not exist";
}
这可以防止在尝试获取不存在的文件大小时出现错误。在操作之前始终验证文件是否存在,以避免警告。
远程文件大小
对于远程文件,我们需要一种不同的方法,因为 filesize 不适用于 HTTP URL。
remote_file.php
<?php
declare(strict_types=1);
function getRemoteFileSize(string $url): ?int {
$headers = get_headers($url, true);
if ($headers && isset($headers['Content-Length'])) {
return (int)$headers['Content-Length'];
}
return null;
}
$fileUrl = "https://example.com/largefile.pdf";
$size = getRemoteFileSize($fileUrl);
echo $size ? "Remote file size: $size bytes" : "Size unavailable";
这使用 HTTP 标头获取远程文件大小。请注意,并非所有服务器都为所有文件提供 Content-Length 标头。
目录大小计算
我们可以递归地计算目录中所有文件的大小总和。
directory_size.php
<?php
declare(strict_types=1);
function getDirectorySize(string $path): int {
$size = 0;
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path)
);
foreach ($files as $file) {
if ($file->isFile()) {
$size += $file->getSize();
}
}
return $size;
}
$dir = "/path/to/directory";
$totalSize = getDirectorySize($dir);
echo "Directory size: " . formatSize($totalSize);
这会递归计算目录中所有文件的大小总和。它使用 PHP 的 SPL 迭代器进行高效的目录遍历。
最佳实践
- 错误处理:始终检查文件是否存在且可读。
- 缓存:如果文件大小可能发生变化,请使用 clearstatcache()。
- 内存:在 32 位系统上处理非常大的文件时要小心。
- 权限:确保正确的文件权限以进行访问。
来源
本教程介绍了 PHP 的 filesize 函数,并通过实际示例展示了其在不同场景下的用法。
作者
列出 所有 PHP 文件系统函数。