Heim  >  Artikel  >  php教程  >  PHP遍历目录返回统计目录大小实例

PHP遍历目录返回统计目录大小实例

WBOY
WBOYOriginal
2016-06-13 09:34:08949Durchsuche

分享一个 PHP遍历目录并返回统计目录大小的方法。
代码:

<?<span>php 
</span><span>$dirname</span> = "test1"<span>; 
</span><span>//</span><span>mkdir($dirname);

//遍历一层目录 </span>
<span>function</span> listdir(<span>$dirname</span><span>) { 
</span><span>$ds</span> = <span>opendir</span>(<span>$dirname</span><span>); 
</span><span>while</span>(<span>$file</span> = <span>readdir</span>(<span>$ds</span><span>)) { 
</span><span>$path</span> = <span>$dirname</span>.'/'.<span>$file</span><span>; 
</span><span>if</span>(<span>is_dir</span>(<span>$file</span><span>)) { 
</span><span>echo</span> "DIR:".<span>$file</span>."<br>"<span>; 
</span><span>if</span>(<span>$file</span> != "." && <span>$file</span> != ".."<span>) { 
listdir(</span><span>$file</span><span>); 
} 
} 
</span><span>else</span><span> { 
</span><span>echo</span> "FILE:".<span>$file</span> . "<br>"<span>; 
} 
} 
}

</span><span>function</span> totdir(<span>$dirname</span>) { <span>//</span><span>对listdir稍加修改 </span>
<span>static</span> <span>$tot</span> = 0<span>; 
</span><span>$ds</span> = <span>opendir</span>(<span>$dirname</span><span>); 
</span><span>while</span>(<span>$file</span> = <span>readdir</span>(<span>$ds</span><span>)) { 
</span><span>$path</span> = <span>$dirname</span>.'/'.<span>$file</span><span>; 
</span><span>if</span>(<span>is_dir</span>(<span>$file</span><span>)) { 
</span><span>//</span><span>echo "DIR:".$file."<br>"; </span>
<span>if</span>(<span>$file</span> != "." && <span>$file</span> != ".."<span>) { 
</span><span>$tot</span> += totdir(<span>$file</span><span>); 
} 
} www</span>.jbxue.<span>com
</span><span>else</span><span> { 
</span><span>//</span><span>echo "FILE:".$file . "<br>"; </span>
<span>$tot</span> += <span>filesize</span>(<span>$path</span><span>); 
} 
}

</span><span>//</span><span>返回总计 </span>
<span>return</span> <span>$tot</span><span>; 
}

listdir(</span><span>$dirname</span><span>);

</span><span>echo</span> totdir(<span>$dirname</span>)." bytes"<span>;

</span>?>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn