Thursday, December 18, 2014
   
Text Size
Login

Php convert filesizes to bytes kb mb gb

What?
Just a quick note on how to format a given filesize and to reduce the display output to a small string, eg:

  1.  196 bytes          : displays as => "196 bytes" 
  2.     12945 bytes        : displays as => "12 Kb" 
  3.     1478515 bytes      : displays as => "1 Mb" 
  4.     8798745455 bytes   : displays as => "8 Gb" 

How?
Source: PHP Share: http://www.phpshare.org

  1.  function formatSizeUnits($bytes
  2.      { 
  3.          if ($bytes >= 1073741824) 
  4.          { 
  5.              $bytes = number_format($bytes / 1073741824, 2) . ' GB'
  6.          } 
  7.          elseif ($bytes >= 1048576) 
  8.          { 
  9.              $bytes = number_format($bytes / 1048576, 2) . ' MB'
  10.          } 
  11.          elseif ($bytes >= 1024) 
  12.          { 
  13.              $bytes = number_format($bytes / 1024, 2) . ' KB'
  14.          } 
  15.          elseif ($bytes > 1) 
  16.          { 
  17.              $bytes = $bytes . ' bytes'
  18.          } 
  19.          else 
  20.          { 
  21.              $bytes = '0 bytes'
  22.          } 
  23.   
  24.          return $bytes
  25.  } 


Inline without a function
Source: Joes Brain: http://www.joellipman.com

  1.  if ($this_file_size >= 1073741824) 
  2.       $this_file_size = number_format($this_file_size / 1073741824, 1) . ' GB'
  3.  elseif ($this_file_size >= 1048576) 
  4.       $this_file_size = number_format($this_file_size / 1048576, 1) . ' MB'
  5.  elseif ($this_file_size >= 1024) 
  6.       $this_file_size = number_format($this_file_size / 1024, 1) . ' KB'
  7.  elseif ($this_file_size > 1) 
  8.       $this_file_size = $this_file_size . ' bytes'
  9.  elseif ($this_file_size == 1) 
  10.       $this_file_size = $this_file_size . ' byte'
  11.  else 
  12.       $this_file_size = '0 bytes'
Add Comment

Name:

Email:

Website:

Message:


Latest Posts

  • Basic Android App using Google Maps and Current Location

    • Wed 17-Dec-14
      Is that how it's spelt? setContentVie( "View". If not try going to build and "clean project". Also ...
      Joel L.  
    • Tue 16-Dec-14
      I have problem in "cannot resolved R" " setContentVie(R .layout.activit y_maps);" :cry: How to solve ...
      LucasR
  • Migrate Joomla! 1.5.x to 2.5.x+

    • Tue 16-Dec-14
      * Categories: - duplicates, I suppose from the multiple times I launched the script. - love the notes ...
      LLiSEIL  
    • Tue 16-Dec-14
      SQL ERror 3 > -- Step 2) Import articles from J15 and insert as articles in J30 INSERT INTO `newbase_j25`.d ...
      LLiSEIL  
    • Tue 16-Dec-14
      I removed the banner part from the script (has no use for that site) and relaunched JMS: SQL Error 2 ...
      LLiSEIL