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.