/ Published in: PHP
Retrieves the filesize of a remote file. I can't take the credit for this function. I grabbed it somewhere online a few years back. Don't remember where.
Expand |
Embed | Plain Text
function remote_filesize($url, $user = "", $pw = "") { $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); { curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } $ok = curl_exec($ch); curl_close($ch); $regex = '/Content-Length:\s([0-9].+?)\s/'; }
Comments
Subscribe to comments
You need to login to post a comment.

Quite useful. In that example, you'll need curl compiled with PHP. Sometimes curl is not available, the same behavior could be achieved using a simple socket (fsockopen) connection in PHP. Using a HEAD request (fputs the corresponding request Headers) and get the value from the headers itself (matching Content-Length:) (as described in line 19. of the curl example). PHP 5 is including nifty function for HTTP connection handling and parsing the headers.
There is lengthy discussion about remote filesize on : http://be.php.net/function.filesize
You can do this without using an output buffer by setting CURLOPT_RETURNTRANSFER to 1
Like so:
function remotefilesize($url, $user = "", $pw = "") { $ch = curlinit($url); curlsetopt($ch, CURLOPTHEADER, 1); curlsetopt($ch, CURLOPTNOBODY, 1); curlsetopt($ch, CURLOPTRETURNTRANSFER, 1);
if (!empty($user) && !empty($pw)) { $headers = array('Authorization: Basic ' . base64encode("$user:$pw")); curlsetopt($ch, CURLOPT_HTTPHEADER, $headers); }
$head = curlexec($ch); curlclose($ch);
$regex = '/Content-Length:\s([0-9].+?)\s/'; $count = preg_match($regex, $head, $matches);
return isset($matches[1]) ? $matches[1] : false; }
Hi, I found this code very useful also.
I got the arharp's version and changed a little bit, here my version:
Regards.
function remotefilesize($url) {
$ch = curlinit($url); curlsetopt($ch, CURLOPTHEADER, 1); curlsetopt($ch, CURLOPTNOBODY, 1); curlsetopt($ch, CURLOPTRETURNTRANSFER, 1); curlexec($ch);
// get some variables $status = curlgetinfo($ch, CURLINFOHTTPCODE); // 200 $filesize = curlgetinfo($ch, CURLINFOCONTENTLENGTHDOWNLOAD); //filesize $fimemime = curlgetinfo($ch, CURLINFOCONTENTTYPE); //mimetype, ex: image/jpeg
curl_close($ch);
if( 200 != $status ) throw new Exception('Arquivo não encontrado!');
return $filesize; }
printf('PHP logo has %s bytes', remotefilesize("http://br2.php.net/images/php.gif") );