Solved

How can I get file size in PHP without opening the full file?

Posted on 2014-09-23
12
333 Views
Last Modified: 2014-09-25
Using fopen() or similar methods load the full file when checking for file size which is a poor implementation, because when using large files, it is AWESOME(!). My file sizes could be as large as 2/3GB. However, in other places, I have seen tutorials like using cURL header responses. But I am on IIS, Windows Server 2008 R2, and IIS does not return the Content-Length header response. So the cURL method is useless.

How can I get file size in PHP without opening the file?
0
Comment
Question by:Md Moinul Islam
  • 5
  • 3
  • 2
  • +1
12 Comments
 
LVL 83

Accepted Solution

by:
Dave Baldwin earned 250 total points
ID: 40340870
Try filesize ( string $filename )  http://php.net/manual/en/function.filesize.php
0
 
LVL 15

Expert Comment

by:Insoftservice
ID: 40340871
<?php

// outputs e.g.  somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?>
0
 

Author Comment

by:Md Moinul Islam
ID: 40340895
Thanks. But the filesize() function does not work good for large files.  I have found the solutions, finally.

@here http://php.net/manual/en/function.filesize.php

CertaiN, commented

<?php
function remote_filesize($url) {
    static $regex = '/^Content-Length: *+\K\d++$/im';
    if (!$fp = @fopen($url, 'rb')) {
        return false;
    }
    if (
        isset($http_response_header) &&
        preg_match($regex, implode("\n", $http_response_header), $matches)
    ) {
        return (int)$matches[0];
    }
    return strlen(stream_get_contents($fp));
}
?>

I think this works good, so far. I will check if there are any problems with that.
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 15

Expert Comment

by:Insoftservice
ID: 40340916
try this one , I hope you are using OS as linux

function filesize2($path) {
  if(@is_dir($path)) {
    return 0;
  }
  $sizeInBytes = @filesize($path);
  if($sizeInBytes===false) {
    $command = "/bin/ls -l ".escapeshellarg($path);
    $ret = trim(exec($command));
    if(!substr_count($ret, "ls:") && !substr_count($ret, "Aucun fichier")) {
      $ret = str_replace("\t", " ", $ret);
      $ret = str_replace("  ", " ", $ret);
      $ret = str_replace("  ", " ", $ret);
      $ret = str_replace("  ", " ", $ret);
      $arr = explode(" ", $ret);
      $sizeInBytes = $arr[4];
    }
  }
  return $sizeInBytes;
}
0
 

Author Comment

by:Md Moinul Islam
ID: 40340992
@insoftservice, perhaps, you didn't read my question in detail. I am on windows server 2008 R2

My previous comment did not work as I expected. Search is on!
0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 40340994
What problem are you having with 'filesize()'?
0
 

Author Comment

by:Md Moinul Islam
ID: 40340996
filesize() will load the whole file into memory to return the file size, therefore utilizing server resources+consumes a lot of time. It's ok for the small files, i think
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 40341362
From the man 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.

Also from the man page, this comment which seems to be the basis of your solution:
http://php.net/manual/en/function.filesize.php#114952

From the stream_get_contents() man page:

stream_get_contents — Reads remainder of a stream into a string

In other words, the solution you propose to use, as you wrote in the question, "load the full file when checking for file size which is a poor implementation..."

Executive summary: There is something in your design pattern that does not make sense.  Perhaps you need to consider a database that will hold the details about these very large files.  Or perhaps you want to consider whether Windows is a useful platform for big data applications (it's not).  A different OS may be a more appropriate solution when you must deal with very large files.
0
 

Author Comment

by:Md Moinul Islam
ID: 40343317
Ray Paseur, thanks a lot for your valuable comments. I can understand that it's windows. But still, isn't there a way to get the file size, like when we click on windows explorer / file properties. In some PHP based file managers, the file information is displayed in the file view panel. Currently I am investigating the source codes of some of those to figure out how those file manager's display file size information.
0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 40343367
The limit (which is mentioned on the man page) is that PHP is a 32-bit application and file sizes that are greater than 2GB cause problems.  If you can find a 64-bit version of PHP, it probably won't have that problem.  But you may find it doesn't have all the extensions you might want.  I'd try to check it for you but I don't have any files that big.
0
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 40343812
filesize() will load the whole file into memory to return the file size, therefore utilizing server resources+consumes a lot of time
In my tests, this does not appear to be true.  Here are the two scripts I used to test.  The first makes a "big" file, the second uses filesize() and then reads the "big" file.  Both scripts output the peak memory usage, allowing you to see that the peak memory usage before and after filesize() is unchanged.  Perhaps you can run these scripts or some variant of them to see what is really happening on your system.

Make a "big" file
<?php // demo/make_big_file.php
error_reporting(E_ALL);

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28524408.html#a40340996

$a = memory_get_peak_usage();
$x = str_repeat('Hello World' . PHP_EOL, 6000);
$b = memory_get_peak_usage();
file_put_contents('storage/big.txt', $x);
unset($x);
$c = memory_get_peak_usage();
var_dump($a, $b, $c);

Open in new window

Outputs: int(229864) int(300816) int(373448)

Check filesize() and read "big" file:
<?php // demo/filesize.php
error_reporting(E_ALL);

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28524891.html#a40342776

$a = memory_get_peak_usage(TRUE);
$s = filesize('storage/big.txt');
$b = memory_get_peak_usage(TRUE);
$x = file_get_contents('storage/big.txt');
$c = memory_get_peak_usage(TRUE);
var_dump($a, $b, $c);

Open in new window

Outputs: int(262144) int(262144) int(524288)

Executive summary: Dave Baldwin gave you the right answer within minutes of seeing the question.
0
 

Author Comment

by:Md Moinul Islam
ID: 40345358
Thanks Ray for your valuable comments. Ok. I am giving that another try.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

789 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question