Hàm đếm số file và tính tổng dung lượng theo 1 đường dẫn thư mục.
- <br />
- function getDirectorySize($path)<br />
- {<br />
- $totalsize = 0;<br />
- $totalcount = 0;<br />
- $dircount = 0;<br />
- if ($handle = opendir ($path))<br />
- {<br />
- while (false !== ($file = readdir($handle)))<br />
- {<br />
- $nextpath = $path . ‘/’ . $file;<br />
- if ($file != ‘.’ && $file != ‘..’ && !is_link ($nextpath))<br />
- {<br />
- if (is_dir ($nextpath))<br />
- {<br />
- $dircount++;<br />
- $result = getDirectorySize($nextpath);<br />
- $totalsize += $result[‘size’];<br />
- $totalcount += $result[‘count’];<br />
- $dircount += $result[‘dircount’];<br />
- }<br />
- elseif (is_file ($nextpath))<br />
- {<br />
- $totalsize += filesize ($nextpath);<br />
- $totalcount++;<br />
- }<br />
- }<br />
- }<br />
- }<br />
- closedir ($handle);<br />
- $total[‘size’] = $totalsize;<br />
- $total[‘count’] = $totalcount;<br />
- $total[‘dircount’] = $dircount;<br />
- return $total;<br />
- }</p>
- <p>function sizeFormat($size)<br />
- {<br />
- if($size<1024)
- {
- return $size." bytes";
- }
- else if($size<(1024*1024))
- {
- $size=round($size/1024,1);
- return $size." KB";
- }
- else if($size<(1024*1024*1024))
- {
- $size=round($size/(1024*1024),1);
- return $size." MB";
- }
- else
- {
- $size=round($size/(1024*1024*1024),1);
- return $size." GB";
- }
- }
Duyệt các thư mục con trong thư mục chính và gọi hàm getDirectorySize() ở trên.
- function folderScan($path) {<br />
- $total_size = 0;<br />
- $files = scandir($path);<br />
- $cleanPath = rtrim($path, ‘/’). ‘/’;</p>
- <p>foreach($files as $t) {<br />
- if ($t<>”.” && $t<>”..”) {<br />
- $currentFile = $cleanPath . $t;<br />
- if (is_dir($currentFile)) {<br />
- $ar = getDirectorySize($currentFile);</p>
- <p>echo “<h4>Details for the path : $currentFile</h4>”;<br />
- echo “Total size : “.sizeFormat($ar[‘size’]).”<br>”;<br />
- echo “No. of files : “.$ar[‘count’].”<br>”;<br />
- echo “No. of directories : “.$ar[‘dircount’].”<br>”;<br />
- }</p>
- <p>}<br />
- }<br />
- }
Thiết lập đường dẫn thư mục chính và chạy chương trình.
- <br />
- $path=”/home/name/public_html”;folderScan($path);<br />