PHP: How to calculate the size of a file
Posted on September 11, 2008, 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!
- September 11, 2008
- article by Gabriel C.
- 2 comments
Related Posts
-
PHP: Calculate the Size, Number of Files & Folders of a Directoryat September 24, 2008 with 3 comments
-
PHP: Get Base (Directory) From File (URL, Path)at September 7, 2008 with 2 comments
-
How to remove an extension from a filenameat September 4, 2008 with 1 comment
-
Extract URL(s) from Link(s) with PHPat September 4, 2008 with 2 comments
-
How to calculate age in PHPat August 29, 2008 with 3 comments

2 Replies to "PHP: How to calculate the size of a file"
December 8, 2008 at 10:04 PM
[...] Probado en bitrepository [...]
April 28, 2009 at 2:50 PM
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];
}