PHP get remote image size function example

WBOY
Release: 2016-07-25 08:54:29
Original
1186 people have browsed it
  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信息,即实现了获取远程图片大小的功能。



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!