欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-03-30 19:59:07
...
  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信息,即实现了获取远程图片大小的功能。