Checking Remote File Size With PHP

If you’re going to grab a file from a remote server using PHP it may be useful to know how large the file is before grabbing it. We can check the remote file headers for the file size by using CURL like so:

function remote_filesize($url, $user = “”, $pw = “”) {
ob_start();
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);

if(!empty($user) && !empty($pw))
{
$headers = array(‘Authorization: Basic ‘ . base64_encode(“$user:$pw”));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}

$ok = curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();

$regex = ‘/Content-Length:s([0-9].+?)s/’;
$count = preg_match($regex, $head, $matches);

return isset($matches[1]) ? $matches[1] : “unknown”;
}

To use the function we could do something like this:

$file=”http://img1.putpic.com/images/main/10/28719152288-orig.jpg”;
echo remote_filesize($file);

Tags: , , ,


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

Leave a Reply