php取得遠端圖片大小函數範例

WBOY
發布: 2016-07-25 08:54:29
原創
1187 人瀏覽過
  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信息,即实现了获取远程图片大小的功能。



來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!