PHP filesize MB/KB conversion

PhpFileFilesize

Php Problem Overview


How can I convert the output of PHP's filesize() function to a nice format with MegaBytes, KiloBytes etc?

like:

  • if the size is less than 1 MB, show the size in KB
  • if it's between 1 MB - 1 GB show it in MB
  • if it's larger - in GB

Php Solutions


Solution 1 - Php

Here is a sample:

<?php
// Snippet from PHP Share: http://www.phpshare.org

    function formatSizeUnits($bytes)
    {
        if ($bytes >= 1073741824)
        {
            $bytes = number_format($bytes / 1073741824, 2) . ' GB';
        }
        elseif ($bytes >= 1048576)
        {
            $bytes = number_format($bytes / 1048576, 2) . ' MB';
        }
        elseif ($bytes >= 1024)
        {
            $bytes = number_format($bytes / 1024, 2) . ' KB';
        }
        elseif ($bytes > 1)
        {
            $bytes = $bytes . ' bytes';
        }
        elseif ($bytes == 1)
        {
            $bytes = $bytes . ' byte';
        }
        else
        {
            $bytes = '0 bytes';
        }
        
        return $bytes;
}
?>

Solution 2 - Php

Even nicer is this version I created from a plugin I found:

function filesize_formatted($path)
{
	$size = filesize($path);
	$units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
	$power = $size > 0 ? floor(log($size, 1024)) : 0;
	return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}

Note from filesize() doc

> Because PHP's integer type is signed and many platforms use 32bit > integers, some filesystem functions may return unexpected results for > files which are larger than 2GB

Solution 3 - Php

A cleaner approach:

function Size($path)
{
	$bytes = sprintf('%u', filesize($path));

	if ($bytes > 0)
	{
		$unit = intval(log($bytes, 1024));
		$units = array('B', 'KB', 'MB', 'GB');

		if (array_key_exists($unit, $units) === true)
		{
			return sprintf('%d %s', $bytes / pow(1024, $unit), $units[$unit]);
		}
	}

	return $bytes;
}

Solution 4 - Php

I think this is a better approach. Simple and straight forward.

public function sizeFilter( $bytes )
{
    $label = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' );
    for( $i = 0; $bytes >= 1024 && $i < ( count( $label ) -1 ); $bytes /= 1024, $i++ );
    return( round( $bytes, 2 ) . " " . $label[$i] );
}

Solution 5 - Php

This is based on @adnan's great answer.

Changes:

  • added internal filesize() call
  • return early style
  • saving one concatentation on 1 byte

And you can still pull the filesize() call out of the function, in order to get a pure bytes formatting function. But this works on a file.


/**
 * Formats filesize in human readable way.
 *
 * @param file $file
 * @return string Formatted Filesize, e.g. "113.24 MB".
 */
function filesize_formatted($file)
{
    $bytes = filesize($file);

    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        return $bytes . ' bytes';
    } elseif ($bytes == 1) {
        return '1 byte';
    } else {
        return '0 bytes';
    }
}

Solution 6 - Php

All the answers to the question uses that 1 kilobyte = 1024 bytes which is wrong! (1 kibibyte = 1024 bytes)

since the question asks to convert file sizes, it should use that 1 kilobyte = 1000 bytes (see https://wiki.ubuntu.com/UnitsPolicy)

function format_bytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB');

    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1000));
    $pow = min($pow, count($units) - 1);

    $bytes /= pow(1000, $pow);

    return round($bytes, $precision) . ' ' . $units[$pow];
}

Solution 7 - Php

This would be a cleaner implementation:

function size2Byte($size) {
	$units = array('KB', 'MB', 'GB', 'TB');
	$currUnit = '';
	while (count($units) > 0  &&  $size > 1024) {
		$currUnit = array_shift($units);
		$size /= 1024;
	}
	return ($size | 0) . $currUnit;
}

Solution 8 - Php

Here is a simple function to convert Bytes to KB, MB, GB, TB :

# Size in Bytes
$size = 14903511;
# Call this function to convert bytes to KB/MB/GB/TB
echo convertToReadableSize($size);
# Output => 14.2 MB

function convertToReadableSize($size){
  $base = log($size) / log(1024);
  $suffix = array("", "KB", "MB", "GB", "TB");
  $f_base = floor($base);
  return round(pow(1024, $base - floor($base)), 1) . $suffix[$f_base];
}

Solution 9 - Php

A complete example.

<?php
    $units = explode(' ','B KB MB GB TB PB');
    echo("<html><body>");
    echo('file size: ' . format_size(filesize("example.txt")));
    echo("</body></html>");


    function format_size($size) {
        
        $mod = 1024;
        
        for ($i = 0; $size > $mod; $i++) {
            $size /= $mod;
        }
         
        $endIndex = strpos($size, ".")+3;
        
        return substr( $size, 0, $endIndex).' '.$units[$i];
    }
?>

Solution 10 - Php

function calcSize($size,$accuracy=2) {
    $units = array('b','Kb','Mb','Gb');
    foreach($units as $n=>$u) {
        $div = pow(1024,$n);
        if($size > $div) $output = number_format($size/$div,$accuracy).$u;
    }
    return $output;
}

Solution 11 - Php

function getNiceFileSize($file, $digits = 2){
    if (is_file($file)) {
        $filePath = $file;
        if (!realpath($filePath)) {
            $filePath = $_SERVER["DOCUMENT_ROOT"] . $filePath;
        }
        $fileSize = filesize($filePath);
        $sizes = array("TB", "GB", "MB", "KB", "B");
        $total = count($sizes);
        while ($total-- && $fileSize > 1024) {
            $fileSize /= 1024;
        }
        return round($fileSize, $digits) . " " . $sizes[$total];
    }
    return false;
}

Solution 12 - Php

//Get the size in bytes
function calculateFileSize($size)
{
   $sizes = ['B', 'KB', 'MB', 'GB'];
   $count=0;
   if ($size < 1024) {
    return $size . " " . $sizes[$count];
    } else{
     while ($size>1024){
        $size=round($size/1024,2);
        $count++;
    }
     return $size . " " . $sizes[$count];
   }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - PhpAdnanView Answer on Stackoverflow
Solution 2 - PhpPiTheNumberView Answer on Stackoverflow
Solution 3 - PhpAlix AxelView Answer on Stackoverflow
Solution 4 - PhpTeffiView Answer on Stackoverflow
Solution 5 - PhpJens A. KochView Answer on Stackoverflow
Solution 6 - PhpmiyuruView Answer on Stackoverflow
Solution 7 - PhpBat FungView Answer on Stackoverflow
Solution 8 - PhpYogi GhorechaView Answer on Stackoverflow
Solution 9 - PhpvdbuilderView Answer on Stackoverflow
Solution 10 - PhpbarnersView Answer on Stackoverflow
Solution 11 - PhpHamedView Answer on Stackoverflow
Solution 12 - PhpTohid DadashnezhadView Answer on Stackoverflow