Get Content-Length of Remote File in PHP
Update: Apparently you can just use the get_headers() function. I am retarded.
I just posted this to the PHP comments, but I figured I’d put here as well. The stat() suite of functions isn’t available to the HTTP stream wrapper in PHP, so if you’re using readfile() to handle downloads (for example, like I was), and it’s coming from a remote site (like it was), then this is useful.
Using the Content-Length response header is very useful for downloads because it is what displays the progress bar and estimated time left to the user; otherwise, they just see “unknown”, which is annoying because they won’t know if they’re downloading something that is 4GB or 4KB. And that letter makes all the difference.
Anyway, use this code.
$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';
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (int)$matches[1];
}
header('Content-Length: ' . $contentLength);
header('Content-Disposition: attachment; filename="' . basename($remoteFile) . '"');
readfile($remoteFile);
Using the CURLOPT_NOBODY cURL option forces cURL to send a HEAD request instead of a GET request. The difference between the two is that HEAD only retrieves the headers. So even if the file you’re requesting is 100GB, it will take the same amount of time for a HEAD request as a file that is 100KB.
For example, doing this:
$contentLength = strlen(file_get_contents($remoteFile));
accomplishes the same thing, but it retrieves the entire body of the resource, which is very, very bad if it’s a very large resource. Not to mention the extra memory required to store the contents of the remote file. Stick to the HEAD requests. I knew they were good for something.
July 25, 2009
Posted in: php

2 Responses
Bro Nameth - July 27, 2009
Plz post moar pix of kittehs n cupcaeks kthxbai
Bob Montgomery - July 30, 2009
“Plz post moar pix of kittehs n cupcaeks kthxbai”
FTW!
Leave a Reply