Php function example for obtaining remote Image size

Source: Internet
Author: User
Php function example for obtaining remote Image size

  1. // Use echo remote_filesize ($ url, $ user = '', $ pw = '');
  2. $ Url = "http://www.aa.com/librarys/images/random/rand_11.jpg"; // Image 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, 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. }

Implementation idea: first, CURL obtains the image to the buffer, and then obtains the Content-Length information of the image in regular expressions, which enables obtaining the remote image size.

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.