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.
Note: This will only work if the remote host is supplying valid content header, namely Content-Length. You cannot otherwise get file size without actually downloading it first.
Note: This will only work if the remote host is supplying valid content header, namely Content-Length. You cannot otherwise get file size without actually downloading it first.
<?php /* Online PHP Examples with Source Code website: http://4evertutorials.blogspot.in/ */ $remoteFileURL = 'http://us.php.net/get/php-5.2.10.tar.bz2/from/this/mirror'; $ch = curl_init($remoteFileURL); 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
0 comments:
Post a Comment