PHP get remote picture size function Example

Source: Internet
Author: User
  1. Usage echo remote_filesize ($url, $user = ", $PW =");
  2. $url = "http://www.aa.com/librarys/images/random/rand_11.jpg";//Picture address
  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, does 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 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 is a content-length field, its value//would now is 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. }
Copy Code

Realization idea: First curl obtains the picture to the buffer, then obtains the picture the Content-length information, namely realizes obtains the remote picture size the function.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.