Thursday, August 27, 2009

File size in human format

I needed to see some file sizes in a human format (in a PHP page) so I created this function some of you might find useful:


/**Returns the size of data (provided in bytes) in a human readable
* format
* @size - the the size of data in bytes
* @author alex from scriptoid.com
*/
function humanSize($size){
if($size < pow(1024, 1)){
return $size . 'Bytes';
}
else if ($size < pow(1024, 2)){
return sprintf("%.2f", $size/pow(1024, 1)) . 'Kb'; //Kilo
}
else if ($size < pow(1024, 3)){
return sprintf("%.2f", $size/pow(1024, 2)) . 'Mb'; //Mega
}
else if ($size < pow(1024, 4)){
return sprintf("%.2f",$size/pow(1024, 3)) . 'Gb'; //Giga
}
else if ($size < pow(1024, 5)){
return sprintf("%.2f",$size / pow(1024, 4)) . 'Tb'; //Tera
}
else if ($size < pow(1024, 6)){
return sprintf("%.2f",$size / pow(1024, 5)) . 'Pb'; //Peta
}
else if ($size < pow(1024, 7)){
return sprintf("%.2f",$size / pow(1024, 6)) . 'Eb'; //Exa
}
else if ($size < pow(1024, 8)){
return sprintf("%.2f",$size /pow(1024, 7)) . 'Zb'; //Zeta
}
else if ($size < pow(1024, 9)){
return sprintf("%.2f",$size /pow(1024, 8)) . 'Yb'; //Yota
}
else{
return 'too big'; //:D
}
}

1 comment:

  1. And the easy way:


    function bytes2Human($bytes) {
    $types = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PT', 'EB', 'ZB', 'YB');
    for($i = 0; $bytes >= 1024 && $i < (count($types) -1); $bytes /= 1024, $i++);
    return(round($bytes, 2) ." ". $types[$i]);
    }

    ReplyDelete