We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

tylerhall on 12/31/69


Tagged

curl http remote filesize file


Versions (?)


Who likes this?

15 people have marked this snippet as a favorite

katxorro70
jkochis
rolandog
irdial
vaaaska
raws
blakeb
demods
clapfouine
fael
vali29
hudge
marteki
huze
jamesming


Get Remote Filesize


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.

  1. function remote_filesize($url, $user = "", $pw = "")
  2. {
  3. $ch = curl_init($url);
  4. curl_setopt($ch, CURLOPT_HEADER, 1);
  5. curl_setopt($ch, CURLOPT_NOBODY, 1);
  6.  
  7. if(!empty($user) && !empty($pw))
  8. {
  9. $headers = array('Authorization: Basic ' . base64_encode("$user:$pw"));
  10. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  11. }
  12.  
  13. $ok = curl_exec($ch);
  14. curl_close($ch);
  15. $head = ob_get_contents();
  16.  
  17. $regex = '/Content-Length:\s([0-9].+?)\s/';
  18. $count = preg_match($regex, $head, $matches);
  19.  
  20. return isset($matches[1]) ? $matches[1] : "unknown";
  21. }

Report this snippet 

Comments

RSS Icon Subscribe to comments
Posted By: adulau on December 28, 2006

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 need to login to post a comment.