Solved

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

Posted on 2014-09-23
12
300 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 82

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
 
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 82

Expert Comment

by:Dave Baldwin
ID: 40340994
What problem are you having with 'filesize()'?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

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 108

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 82

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 108

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Wordpress type image upload 10 32
resizeing PHP image 2 23
Instering to MySQL table 5 22
Insert data into database 2 15
Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

747 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now