In this tutorial, i am going to tell you how to get directory size in PHP Laravel.
As all knows, PHP has inbuilt function to get file size using filesize()
method but ever you think how to get directory size in PHP or how to read directory files and sub directory within directory?
A folder may have many files and have subfolder that contains many files too.
So here you will know how to iterate over folders and their files.
PHP function will return size in bytes so first we write a function to convert bytes to Kilobyte, Megabyte, Gigabyte and Terabyte etc.
PHP Function to format size
- function formatSize($bytes){
- $kb = 1024;
- $mb = $kb * 1024;
- $gb = $mb * 1024;
- $tb = $gb * 1024;
- if (($bytes >= 0) && ($bytes < $kb)) {
- return $bytes . ' B';
- } elseif (($bytes >= $kb) && ($bytes < $mb)) {
- return ceil($bytes / $kb) . ' KB';
- } elseif (($bytes >= $mb) && ($bytes < $gb)) {
- return ceil($bytes / $mb) . ' MB';
- } elseif (($bytes >= $gb) && ($bytes < $tb)) {
- return ceil($bytes / $gb) . ' GB';
- } elseif ($bytes >= $tb) {
- return ceil($bytes / $tb) . ' TB';
- } else {
- return $bytes . ' B';
- }
- }
Now we will write a function to scan directory and return size of directory.
PHP Function to return directory size
- function folderSize($dir){
- $total_size = 0;
- $count = 0;
- $dir_array = scandir($dir);
- foreach($dir_array as $key=>$filename){
- if($filename!=".." && $filename!="."){
- if(is_dir($dir."/".$filename)){
- $new_foldersize = foldersize($dir."/".$filename);
- $total_size = $total_size+ $new_foldersize;
- }else if(is_file($dir."/".$filename)){
- $total_size = $total_size + filesize($dir."/".$filename);
- $count++;
- }
- }
- }
- return $total_size;
- }
- $folder_path = "folder path";
- echo formatSize(folderSize($folder_path));