note 92462 added to function.filesize
| From: | tmont at osu1 dot php dot net | Date: | Sat, 25 Jul 2009 09:05:22 +0000 |
| Subject: | note 92462 added to function.filesize | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-158716@lists.php.net to get a copy of this message | ||
Here's the best way (that I've found) to get the size of a remote file. Note that HEAD
requests don't get the actual body of the request, they just retrieve the headers. So making a
HEAD request to a resource that is 100MB will take the same amount of time as a HEAD request to a
resource that is 1KB.
<?php
$remoteFile = 'http://us.php.net/get/php-5.2.10.tar.bz2/from/this/mirror';
$ch = curl_init($remoteFile);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the
PHP example we're using here)
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
echo 'cURL failed';
exit;
}
$contentLength = 'unknown';
$status = 'unknown';
if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
$status = (int)$matches[1];
}
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (int)$matches[1];
}
echo 'HTTP Status: ' . $status . "\n";
echo 'Content-Length: ' . $contentLength;
?>
Result:
HTTP Status: 302
Content-Length: 8808759
----
Server IP: 209.41.74.194
Probable Submitter: 70.179.22.151
----
Manual Page -- http://www.php.net/manual/en/function.filesize.php
Edit -- https://master.php.net/note/edit/92462
Del: integrated -- https://master.php.net/note/delete/92462/integrated
Del: useless -- https://master.php.net/note/delete/92462/useless
Del: bad code -- https://master.php.net/note/delete/92462/bad+code
Del: spam -- https://master.php.net/note/delete/92462/spam
Del: non-english -- https://master.php.net/note/delete/92462/non-english
Del: in docs -- https://master.php.net/note/delete/92462/in+docs
Del: other reasons-- https://master.php.net/note/delete/92462
Reject -- https://master.php.net/note/reject/92462
Search -- https://master.php.net/manage/user-notes.php