Home  >  Article  >  Backend Development  >  Example of getting the size of a remote image in php_PHP tutorial

Example of getting the size of a remote image in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:25:16756browse

Just look at the code, it’s very clear

Copy the code The code is as follows:

//Usage echo remote_filesize( $url,$user='',$pw='');
$url = "http://www.aa.com/librarys/images/random/rand_11.jpg";//To be replaced here 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 get the image into the buffer with CURL, and then get the Content-Length information of the image using regular expression.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/825146.htmlTechArticleLet’s look at the code directly. The easy-to-understand copy of the code is as follows: //Usage echo remote_filesize($url,$ user='',$pw=''); $url = "http://www.aa.com/librarys/images/random/rand_11.jpg";/...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn