Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP filesize() On Files > 2 GB

I have been struggeling on how to get the valid filesize of a file that is >= 2 GB in PHP.

Example
Here I am checking the filesize of a file that is 3,827,394,560 bytes large with the filesize() function:

echo "The file is " . filesize('C:\MyFile.rar') . " bytes.";

Result
This is what it returns:

The file is -467572736 bytes.

Background
PHP uses signed integers, which means that the maximum number it can represent is 2,147,483,647 (+/- 2 GB).
This is where it is limited.

like image 428
René Sackers Avatar asked Feb 19 '12 02:02

René Sackers


2 Answers

The solution I tried and apparently works is to use the "Size" property of the COM FileObject. I am not entirely sure what type it uses.

This is my code:

function real_filesize($file_path)
{
    $fs = new COM("Scripting.FileSystemObject");
    return $fs->GetFile($file_path)->Size;
}

It's simply called as following:

$file = 'C:\MyFile.rar';
$size = real_filesize($file);
echo "The size of the file is: $size";

Result

The size of the file is: 3,827,394,560 bytes

like image 162
René Sackers Avatar answered Sep 19 '22 03:09

René Sackers


http://us.php.net/manual/en/function.filesize.php#102135 gives a complete and correct means for finding the size of a file larger than 2GB in PHP, without relying on OS-specific interfaces.

The gist of it is that you first use filesize to get the "low" bits, then open+seek the file to determine how many multiples of 2GB it contains (the "high" bits).

like image 20
Borealid Avatar answered Sep 20 '22 03:09

Borealid