PHP filesize()函数
filesize()函数用于获取指定文件的大小(字节数)。
语法
int filesize ( string $filename )
参数说明
| 参数 |
描述 |
filename |
要获取大小的文件路径。可以是相对路径或绝对路径 |
返回值
- 成功时返回文件大小的字节数(整数)
- 失败时返回
false 并生成一个 E_WARNING 级别的错误
示例代码
示例1:获取文件大小
<?php
// 获取当前目录下test.txt文件的大小
$filename = 'test.txt';
$size = filesize($filename);
if ($size !== false) {
echo "文件 {$filename} 的大小是: {$size} 字节";
} else {
echo "无法获取文件大小";
}
?>
示例2:格式化显示文件大小
<?php
function formatSizeUnits($bytes) {
if ($bytes >= 1073741824) {
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
$bytes = number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
$bytes = number_format($bytes / 1024, 2) . ' KB';
} elseif ($bytes > 1) {
$bytes = $bytes . ' 字节';
} elseif ($bytes == 1) {
$bytes = $bytes . ' 字节';
} else {
$bytes = '0 字节';
}
return $bytes;
}
$filename = 'example.pdf';
$size = filesize($filename);
echo "文件名: " . $filename . "<br>";
echo "原始大小: " . $size . " 字节<br>";
echo "格式化后: " . formatSizeUnits($size);
?>
示例3:检查多个文件的大小
<?php
$files = [
'file1.txt',
'file2.jpg',
'file3.pdf'
];
echo "<table border='1'>";
echo "<tr><th>文件名</th><th>大小(字节)</th><th>格式化大小</th></tr>";
foreach ($files as $file) {
if (file_exists($file)) {
$size = filesize($file);
$formatted = formatSizeUnits($size);
echo "<tr><td>{$file}</td><td>{$size}</td><td>{$formatted}</td></tr>";
} else {
echo "<tr><td>{$file}</td><td colspan='2'>文件不存在</td></tr>";
}
}
echo "</table>";
?>
注意事项
重要提示:
- 由于 PHP 的整数类型是有符号的,
filesize() 在大文件(超过 2GB)时可能返回错误结果
- 某些文件系统(如 FAT)可能不支持大文件,建议使用
fseek() 和 ftell() 处理大文件
- 函数的结果会被缓存,使用
clearstatcache() 来清除缓存
- 确保文件存在且有读取权限,否则会返回
false
示例4:处理缓存问题
<?php
// 第一次获取文件大小
$filename = 'data.txt';
$size1 = filesize($filename);
echo "第一次获取: " . $size1 . " 字节<br>";
// 假设此时文件被修改(大小改变)
// 清除状态缓存
clearstatcache();
// 再次获取文件大小
$size2 = filesize($filename);
echo "第二次获取: " . $size2 . " 字节<br>";
// 检查是否需要清除缓存
$stat = stat($filename);
if (time() - $stat['mtime'] < 5) { // 如果5秒内修改过
clearstatcache();
echo "文件最近被修改,已清除缓存";
}
?>
相关函数
file_exists() - 检查文件或目录是否存在
fstat() - 通过已打开的文件指针获取文件信息
disk_free_space() - 返回目录中的可用空间
stat() - 获取文件信息