欢迎访问宙启技术站
智能推送

如何使用PHP函数计算文件大小并格式化显示

发布时间:2023-07-04 05:26:28

要计算文件的大小并格式化显示,您可以使用以下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 . ' bytes';
    } elseif ($bytes == 1) {
        $bytes = $bytes . ' byte';
    } else {
        $bytes = '0 bytes';
    }
    return $bytes;
}

$fileSize = filesize('path/to/file'); // 替换为您要计算大小的文件的路径
$formattedSize = formatSizeUnits($fileSize);
echo '文件大小: ' . $formattedSize;

在上面的代码中:

- 首先定义了一个formatSizeUnits函数,该函数将字节大小作为参数,并根据大小将其格式化为GB,MB,KB,字节。

- 然后,通过调用filesize函数获取要计算大小的文件的大小,并将其存储在$fileSize变量中。

- 最后,通过调用formatSizeUnits函数并将$fileSize作为参数传递,将大小格式化为可读格式,并将其存储在$formattedSize变量中。

- 最后,使用echo语句将格式化大小显示在屏幕上。

请确保将'path/to/file'替换为要计算大小的实际文件的路径。