Php _ php instance for obtaining the volume of remote Images

Source: Internet
Author: User
Sometimes, we need to know the size of the remote image. How can PHP do this? Let's look at the code. It's easy to understand.

The Code is as follows:


// Use echo remote_filesize ($ url, $ user = '', $ pw = '');
$ Url = "http://www.aa.com/librarys/images/random/rand_11.jpg"; // here you want to change to your image address
Echo remote_filesize ($ url, $ user = '', $ pw = '');

Function remote_filesize ($ uri, $ user = '', $ pw = '')
{
// Start output buffering
Ob_start ();
// Initialize curl with given uri
$ Ch = curl_init ($ uri); // make sure we get the header
Curl_setopt ($ ch, CURLOPT_HEADER, 1); // make it a http HEAD request
Curl_setopt ($ ch, CURLOPT_NOBODY, 1); // if auth is needed, do it here
If (! Empty ($ user )&&! Empty ($ pw ))
{
$ Headers = array ('authorization: Basic '. base64_encode ($ user.': '. $ pw ));
Curl_setopt ($ ch, CURLOPT_HTTPHEADER, $ headers );
}
$ Okay = curl_exec ($ ch );
Curl_close ($ ch); // get the output buffer
$ Head = ob_get_contents (); // clean the output buffer and return to previous // buffer settings
Ob_end_clean (); // gets you the numeric value from the Content-Length // field in the http header
$ Regex = '/Content-Length: \ s ([0-9]. + ?) \ S /';
$ Count = preg_match ($ regex, $ head, $ matches); // if there was a Content-Length field, its value // will now be in $ matches [1]
If (isset ($ matches [1])
{
$ Size = $ matches [1];
}
Else
{
$ Size = 'unknown ';
}
$ Last_mb = round ($ size/(1024*1024), 3 );
$ Last_kb = round ($ size/1024,3 );
Return $ last_kb. 'kb/'. $ last_mb. 'mb ';
}


The idea of the function is to first obtain the image to the buffer using CURL, and then obtain the Content-Length information of the image through regular expression.

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.