» Birthday Bundle - Over $400 worth of Envato files for just $20

PHP: How to calculate the size of a file

Posted on September 11, 2008, Filled under PHP,  Bookmark it

This function calculates the size of a file in bytes, kilobytes, megabytes and gigabytes.

<?php
function get_file_size($filename, $size_in = 'MB')
{
$size_in_bytes = filesize($filename);

// Precision: decimals at the end for each type of size

if($size_in == 'B')
{
$size = $size_in_bytes;
$precision = 0;
}
elseif($size_in == 'KB')
{
$size = (($size_in_bytes / 1024));
$precision = 2;
}
elseif($size_in == 'MB')
{
$size = (($size_in_bytes / 1024) / 1024);
$precision = 2;
}
elseif($size_in == 'GB')
{
$size = (($size_in_bytes / 1024) / 1024) / 1024;
$precision = 2;
}

$size = round($size, $precision);

	return $size.' '.$size_in;
}

$file = '/path/to/public_html/folder/my_file.zip';

# 1st argument: path to file
# 2st argument: calculate in: B (Bytes), KB (Kilobytes), MB (Megabytes), GB (Gigabytes)

echo get_file_size($file, 'MB');
?>

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

Related Posts

2 Replies to "PHP: How to calculate the size of a file"

  1. I think, that better function is this :

    function get_file_size($file_size) {

    if (!is_int($file_size)){
    echo “Input not INTEGER!!!!”;
    return false;
    }

    $jednotka = 0;

    $size[0] = ‘B’;
    $size[1] = ‘KB’;
    $size[2] = ‘MB’;
    $size[4] = ‘GB’;
    $size[5] = ‘TB’;

    while($file_size>9999){
    $file_size = $file_size / 1024;
    $jednotka++;
    }

    $file_size = round($file_size, 2);
    return $file_size.’ ‘.$size[$jednotka];
    }

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)