php读取文件大小

获取本地文件大小filesize()就可以了,但是如何获取远程文件的大小呢? 这里介绍三个方法来获取远程文件的大小.

方法1:get_headers

  1. <?php 
  2. 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. ?> 

此处可以直接根据Content-Length来获取到远程文件的大小了.

方法2: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. {
  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. }

方法3:socket

  1. function getFileSize($url)
  2. {
  3. $url = parse_url($url);
  4. if($fp = @fsockopen($url['host'],emptyempty($url['port'])?80:$url['port'],$error))
  5. {
  6. fputs($fp,"GET ".(emptyempty($url['path'])?'/':$url['path'])." HTTP/1.1 ");
  7. fputs($fp,"Host:$url[host] ");
  8. while(!feof($fp))
  9. {
  10. $tmp = fgets($fp);
  11. if(trim($tmp) == '')
  12. {
  13. break;
  14. }
  15. elseif(preg_match('/Content-Length:(.*)/si',$tmp,$arr))
  16. {
  17. return trim($arr[1]);
  18. }
  19. }
  20. return null;
  21. }
  22. else 
  23. {
  24. return null;
  25. }
  26. }

方法4:file_get_contents

  1. $fCont = file_get_contents("http://www.mg27.com/1.html");
  2. echo strlen($fCont)/1024;
原文地址:https://www.cnblogs.com/smilevv/p/13261029.html