function humanFileSize($size) { if ($size >= 1073741824) { $fileSize = round($size / 1024 / 1024 / 1024,1) . 'GB'; } elseif ($size >= 1048576) { $fileSize = round($size / 1024 / 1024,1) . 'MB'; } elseif($size >= 1024) { $fileSize = round($size / 1024,1) . 'KB'; } else { $fileSize = $size . ' bytes'; } return $fileSize; }
... works great except: I can't manually choose in what format I need to display, say i want to show in MB only whatever the file size is. Currently if its in the GB range, it would only show in GB.
Also, how do I limit the decimal to 2?
You need to display the size of a file in kilobytes, megabytes, or gigabytes. Instead of displaying file sizes as 1,073,741,824 bytes, you want an approximate, human-readable size, such as 1 GB.
Using ls to Show File Size in Human-Readable FormatUsing the -h flag shows the total size of files and directories and the individual size of each file and directory in a human-readable format. You can also specify the block size for displaying the file size. By default, the file size is in bytes.
A human-readable medium or human-readable format is any encoding of data or information that can be naturally read by humans.
Try something like this:
function humanFileSize($size,$unit="") { if( (!$unit && $size >= 1<<30) || $unit == "GB") return number_format($size/(1<<30),2)."GB"; if( (!$unit && $size >= 1<<20) || $unit == "MB") return number_format($size/(1<<20),2)."MB"; if( (!$unit && $size >= 1<<10) || $unit == "KB") return number_format($size/(1<<10),2)."KB"; return number_format($size)." bytes"; }
There is great example by Jeffrey Sambells:
function human_filesize($bytes, $dec = 2) { $size = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); $factor = floor((strlen($bytes) - 1) / 3); return sprintf("%.{$dec}f", $bytes / pow(1024, $factor)) . @$size[$factor]; } print human_filesize(filesize('example.zip'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With