Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

File size of big files #15

Open
luzik opened this issue Dec 15, 2017 · 2 comments
Open

File size of big files #15

luzik opened this issue Dec 15, 2017 · 2 comments

Comments

@luzik
Copy link

luzik commented Dec 15, 2017

Files like 4GB are do not shows size at all

@halgatewood
Copy link
Owner

I'm using the built-in PHP function filesize. Here is a note on that page:

Note: 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.
http://php.net/manual/en/function.filesize.php

@luzik
Copy link
Author

luzik commented Feb 23, 2018

In user notes section of this manual page there are few resolution for this issue.
Please consider using something like:

<?php
/**
* Return file size (even for file > 2 Gb)
* For file size over PHP_INT_MAX (2 147 483 647), PHP filesize function loops from -PHP_INT_MAX to PHP_INT_MAX.
*
* @param string $path Path of the file
* @return mixed File size or false if error
*/
function realFileSize($path)
{
    if (!file_exists($path))
        return false;

    $size = filesize($path);
    
    if (!($file = fopen($path, 'rb')))
        return false;
    
    if ($size >= 0)
    {//Check if it really is a small file (< 2 GB)
        if (fseek($file, 0, SEEK_END) === 0)
        {//It really is a small file
            fclose($file);
            return $size;
        }
    }
    
    //Quickly jump the first 2 GB with fseek. After that fseek is not working on 32 bit php (it uses int internally)
    $size = PHP_INT_MAX - 1;
    if (fseek($file, PHP_INT_MAX - 1) !== 0)
    {
        fclose($file);
        return false;
    }
    
    $length = 1024 * 1024;
    while (!feof($file))
    {//Read the file until end
        $read = fread($file, $length);
        $size = bcadd($size, $length);
    }
    $size = bcsub($size, $length);
    $size = bcadd($size, strlen($read));
    
    fclose($file);
    return $size;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants