答案是使用PHP递归函数遍历目录中所有文件和子目录,累加文件大小以计算总大小。函数首先检查路径是否为有效目录,打开目录后逐个读取条目,跳过“.”和“..”,对文件直接获取大小,对子目录递归调用自身。最终返回总字节数,并可通过格式化函数转换为KB、MB或GB显示。示例代码包含错误处理与资源释放,适用于常规目录统计,但需注意权限、执行时间及符号链接可能导致的无限循环问题,也可用RecursiveIteratorIterator优化性能。

使用PHP递归函数计算目录大小 是一个常见的需求,特别是在开发文件管理系统或需要监控磁盘使用情况时。PHP本身不提供直接获取整个目录大小的函数,但可以通过递归遍历目录中的所有文件并累加其大小来实现。
function getDirectorySize($path) {
$totalSize = 0;
<pre class='brush:php;toolbar:false;'>// 检查路径是否存在且为目录
if (!is_dir($path)) {
return 0;
}
// 打开目录句柄
$dir = opendir($path);
if ($dir === false) {
return 0;
}
while (($file = readdir($dir)) !== false) {
// 跳过当前目录和上级目录符号
if ($file == '.' || $file == '..') {
continue;
}
$fullPath = $path . '/' . $file;
if (is_file($fullPath)) {
$totalSize += filesize($fullPath);
} elseif (is_dir($fullPath)) {
$totalSize += getDirectorySize($fullPath); // 递归调用
}
}
closedir($dir);
return $totalSize;}
$directory = '/path/to/your/directory';
$sizeInBytes = getDirectorySize($directory);
<p>// 将字节转换为 KB、MB 或 GB
function formatSize($bytes) {
if ($bytes < 1024) {
return $bytes . ' B';
} else if ($bytes < 1024 <em> 1024) {
return round($bytes / 1024, 2) . ' KB';
} else if ($bytes < 1024 </em> 1024 <em> 1024) {
return round($bytes / (1024 </em> 1024), 2) . ' MB';
} else {
return round($bytes / (1024 <em> 1024 </em> 1024), 2) . ' GB';
}
}</p><p>echo "目录大小:" . formatSize($sizeInBytes);</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/863">
<img src="https://img.php.cn/upload/ai_manual/001/246/273/68b6ce0cd568b995.png" alt="办公小浣熊">
</a>
<div class="aritcle_card_info">
<a href="/ai/863">办公小浣熊</a>
<p>办公小浣熊是基于商汤大语言模型的原生数据分析产品,</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="办公小浣熊">
<span>77</span>
</div>
</div>
<a href="/ai/863" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="办公小浣熊">
</a>
</div>
set_time_limit(300);
is_link() 判断)RecursiveIteratorIterator 和 RecursiveDirectoryIterator 类代替手动递归基本上就这些。这个递归方法简单有效,适合大多数场景下的目录大小统计需求。
立即学习“PHP免费学习笔记(深入)”;
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号