>  기사  >  백엔드 개발  >  php获取远程图片大小函数示例

php获取远程图片大小函数示例

WBOY
WBOY원래의
2016-07-25 08:54:291176검색
  1. //用法 echo remote_filesize($url,$user='',$pw='');
  2. $url = "http://www.aa.com/librarys/images/random/rand_11.jpg";//图片地址
  3. echo remote_filesize($url,$user='',$pw='');
  4. function remote_filesize($uri,$user='',$pw='')
  5. {
  6. // start output buffering
  7. ob_start();
  8. // initialize curl with given uri
  9. $ch = curl_init($uri); // make sure we get the header
  10. curl_setopt($ch, CURLOPT_HEADER, 1); // make it a http HEAD request
  11. curl_setopt($ch, CURLOPT_NOBODY, 1); // if auth is needed, do it here
  12. if (!empty($user) && !empty($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); // get the output buffer
  19. $head = ob_get_contents(); // clean the output buffer and return to previous // buffer settings
  20. ob_end_clean(); // gets you the numeric value from the Content-Length // field in the http header
  21. $regex = '/Content-Length:\s([0-9].+?)\s/';
  22. $count = preg_match($regex, $head, $matches); // if there was a Content-Length field, its value // will now be in $matches[1]
  23. if (isset($matches[1]))
  24. {
  25. $size = $matches[1];
  26. }
  27. else
  28. {
  29. $size = 'unknown';
  30. }
  31. $last_mb = round($size/(1024*1024),3);
  32. $last_kb = round($size/1024,3);
  33. return $last_kb . 'KB / ' . $last_mb.' MB';
  34. }
复制代码

实现思路: 先CURL获取图片到缓冲区,然后正则获取图片的Content-Length信息,即实现了获取远程图片大小的功能。



성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.