Saturday, November 8, 2008

PHP: Get remote File Size

This time I'm providing a sample code with example to get the file size from a remote server/website. The file can be any type, image, video, audio, text, whatever.

This example is built using the fsockopen() function of PHP. Just passing the HTTP 'HEAD' call to the provided link, and take the HTTP response from the remote server. After that just parsing the 'Content-Length' from the response header. What you have to do, just use the function, and pass any valid URL to the function. It will return the content length as bytes.

## Example #1
## retriving the image file size from
print get_remote_image_size('') . "\n";

## Example #1
## retriving the image file size from facebook image
print get_remote_image_size('')."\n";

## sample function that takes url, and
## returns the content length for that url
function get_remote_image_size($url){

$url = preg_replace('/http:\/\//','',$url);
if( preg_match('/(.*?)(\/.*)/', $url, $match) ){

$domain = $match[1];
$portno = 80;
$method = "HEAD";
$url = $match[2];
# print "$domain\n$url\n";

$http_response = "";
$http_request .= $method." ".$url ." HTTP/1.0\r\n";
$http_request .= "\r\n";

$fp = fsockopen($domain, $portno, $errno, $errstr);
fputs($fp, $http_request);
while (!feof($fp)) $http_response .= fgets($fp, 128);

$header = "Content-Length";
$ret_str = "";
if( preg_match("/Content\-Length: (\d+)/i",$http_response, $match ) ){
return $match[1];
return -1;


Remember, this function will return -1 if the URL format is not correct or any other internal processing error. You can enhance the performance of the function yourself. Just depends how you'll use it.

1 comment:

Anonymous said...

If the above doesn't work for you, try this. It worked better for me.

function remote_filesize($url, $user = "", $pw = "") {
$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);
$head = ob_get_contents();

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

return isset($matches[1]) ? $matches[1] : "unknown";

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...