PHP 获取远程文件大小常用方法总结

php有很多方法可以获取远程文件大小的,最常用的就有fsockopen、file_get_contents、curl函数,下面我来给各位总结一下.

1、fsockopen,代码如下:

  1. <?php
  2. function getFileSize($url){
  3. $url = parse_url($url);
  4. if($fp = @fsockopen($url['host'],emptyempty($url['port'])?80:$url['port'],$error)){
  5. fputs($fp,"GET ".(emptyempty($url['path'])?'/':$url['path'])." HTTP/1.1rn");
  6. fputs($fp,"Host:$url[host]rnrn");
  7. while(!feof($fp)){
  8. $tmp = fgets($fp);
  9. if(trim($tmp) == ''){
  10. break;
  11. }else if(preg_match('/Content-Length:(.*)/si',$tmp,$arr)){
  12. return trim($arr[1]);
  13. }
  14. }
  15. return null;
  16. }else{
  17. return null;
  18. }
  19. }
  20. //调用方法
  21. echo getFileSize("http://www.phpfensi.com/")
  22. ?>

2、使用file_get_contents(),代码如下:

  1. <?php
  2. $file = file_get_contents($url);
  3. echo strlen($file);
  4. ?>

3. 使用get_headers(),代码如下:

  1. <?php
  2. $header_array = get_headers($url, true);
  3. //返回结果
  4. Array
  5. (
  6. [0] => HTTP/1.1 200 OK
  7. [Date] => Sat, 29 May 2004 12:28:14 GMT
  8. [Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux)
  9. [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
  10. [ETag] => "3f80f-1b6-3e1cb03b"
  11. [Accept-Ranges] => bytes
  12. [Content-Length] => 438
  13. [Connection] => close
  14. [Content-Type] => text/html
  15. )
  16. $size = $header_array['Content-Length'];
  17. echo $size;
  18. ?>

4.curl,代码如下:

  1. function remote_filesize($uri,$user='',$pw='')
  2. {
  3. // start output buffering
  4. ob_start();
  5. // initialize curl with given uri
  6. $ch = curl_init($uri);
  7. // make sure we get the header
  8. curl_setopt($ch, CURLOPT_HEADER, 1);
  9. // make it a http HEAD request
  10. curl_setopt($ch, CURLOPT_NOBODY, 1);
  11. // if auth is needed, do it here
  12. if (!emptyempty($user) && !emptyempty($pw))
  13. {
  14. $headers = array('Authorization: Basic ' . base64_encode($user.':'.$pw));
  15. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  16. }
  17. $okay = curl_exec($ch);
  18. curl_close($ch);
  19. // get the output buffer
  20. $head = ob_get_contents();
  21. // clean the output buffer and return to previous
  22. // buffer settings
  23. ob_end_clean();
  24. echo '<br>head-->'.$head.'<----end <br>';
  25. // gets you the numeric value from the Content-Length
  26. // field in the http header
  27. $regex = '/Content-Length:s([0-9].+?)s/';
  28. $count = preg_match($regex, $head, $matches);
  29. // if there was a Content-Length field, its value
  30. // will now be in $matches[1]
  31. if (isset($matches[1]))
  32. { //开源代码phpfensi.com
  33. $size = $matches[1];
  34. }
  35. else
  36. {
  37. $size = 'unknown';
  38. }
  39. //$last=round($size/(1024*1024),3);
  40. //return $last.' MB';
  41. return $size;
  42. }