php view request header information for remote image size sharing

  • 2020-12-09 00:46:31
  • OfStack

To get the size of a remote image, a common practice is to retrieve the content of the remote image and calculate the length using strlen, which requires the image to be downloaded before calculation. If the picture is very large, then the network transmission will take a lot of time, the efficiency is obviously low. I offer one way to improve efficiency, mainly by using http headers.

When a web page is visited, the server returns the header of the request, with ES5en-ES6en representing the size of the page content requested. If the request is for an image, then ES7en-ES8en represents the size of the image. Based on this, you only need to send the head request to get the returned header information for OK. In php, you can get the header information through the fsockopen method. The code is as follows:


$fp = fsockopen("www.baidu.com", 80, $errno, $errstr, 30);
if ($fp) {
    // Here the request is set to HEAD We have to do is 
    $out = "HEAD /img/baidu_sylogo1.gif HTTP/1.1\r\n";
    $out .= "Host: www.baidu.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        $header = fgets($fp);
        if (stripos($header, 'Content-Length') !== false) {
            $size = trim(substr($header, strpos($header, ':') + 1));
            echo $size;
        }
    }
    fclose($fp);
} else {
    echo "$errstr ($errno)";
}

As with the GET request, just set the request type GET to HEAD. Request the host and path, modify into their own needs can be.

Summary:

get_headers can also be used in php to get header information, but I have tested this function, GET request, see php function get_headers request or HEAD request.

Other servers may block HEAD requests, but if they are blocked, the GET request will have to be used honestly. If you want to do this, you can simply use the ready-made function getimagesize.


Related articles: