PHP >2 GB filesize

Linux howto's, compile information, information on whatever we learned on working with linux, MACOs and - of course - Products of the big evil....
Post Reply
User avatar
^rooker
Site Admin
Posts: 1483
Joined: Fri Aug 29, 2003 8:39 pm

PHP >2 GB filesize

Post by ^rooker »

[PROBLEM]
PHP does not have unsigned integers.
In the version which I'm using (v5.2.6-1) it the function "filesize()" reports a negative value for files larger than 2GB. :(

So, my testfile had 3549599744 Bytes (~3.5GB).
The following code would output a negative number (=the signed value of 3549599744):
ouch: -745367552

Code: Select all

<?php
$filesize = filesize($large_file);
if ($filesize <= 0)
{
   printf(
}
else
{
   echo "ok!";
}
?>
[SOLUTION]
Since I'm working on a Debian stable (for production usage), I'm stuck with the current PHP version (and I don't even know if this behavior is changed), I had to find a workaround.

Luckily (or actually, unfortunately), others have the same problem and offered infos about workarounds.

so instead of:

Code: Select all

$filesize = filesize($large_file);
use "%u" to reformat it to an unsigned value (that can even exceed 4GB):

Code: Select all

$filesize += sprintf("%u", @filesize($large_file));
It's a dirty hack, because the value is reformatted to an unsigned value, converted to a string by 'sprintf()' and then forced to a numeric type by the '+=' operator. yikes! :shock:

But it works...
Jumping out of an airplane is not a basic instinct. Neither is breathing underwater. But put the two together and you're traveling through space!
User avatar
^rooker
Site Admin
Posts: 1483
Joined: Fri Aug 29, 2003 8:39 pm

Output of >2GB filesize

Post by ^rooker »

If you want to output the large value, you cannot use:

Code: Select all

printf("Filesize: %d\n", $filesize);
as it will crop the value to the positive maximum of a signed int: 2804232192.

You can however use 'float' and reduce the decimals to zero:

Code: Select all

printf(Filesize: %.0f\n", $filesize);
This can handle values larger than 32bit unsigned int.
Jumping out of an airplane is not a basic instinct. Neither is breathing underwater. But put the two together and you're traveling through space!
Post Reply