要获取PHP目录的大小,可以使用以下代码:
<?php
function getDirectorySize($dir) {
$size = 0;
$files = scandir($dir);
foreach ($files as $file) {
if ($file == '.' || $file == '..') continue;
$path = $dir . '/' . $file;
if (is_file($path)) {
$size += filesize($path);
} elseif (is_dir($path)) {
$size += getDirectorySize($path);
}
}
return $size;
}
$directory = 'your_directory_path'; // 替换为你要计算大小的目录路径
$size = getDirectorySize($directory);
echo "目录大小: " . formatSizeUnits($size) . "n";
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 = '1 byte';
} else {
$bytes = '0 bytes';
}
return $bytes;
}
?> 这段代码定义了一个名为getDirectorySize的函数,它递归地遍历指定目录及其子目录,并计算所有文件的总大小,使用formatSizeUnits函数将字节大小转换为适当的单位(GB、MB、KB或字节),输出目录的大小。

(图片来源网络,侵删)

(图片来源网络,侵删)
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/48652.html