Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

human readable file size

Tags:

php

filesize

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?

like image 530
eozzy Avatar asked Mar 03 '13 16:03

eozzy


People also ask

What is human readable size?

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.

How do I determine the size of a human readable file?

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.

What is a human readable file?

A human-readable medium or human-readable format is any encoding of data or information that can be naturally read by humans.


2 Answers

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"; } 
like image 125
Niet the Dark Absol Avatar answered Oct 02 '22 10:10

Niet the Dark Absol


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')); 
like image 35
Vaidas Avatar answered Oct 02 '22 12:10

Vaidas