PHP View request header information how to get a remote picture size share _php instance

Source: Internet
Author: User

If you want to get the size of a remote picture, it's a common practice to get the contents of the remote picture back and then use strlen to compute the length, which requires downloading the pictures before you can compute them. If the picture is very large, then the network transmission will take a lot of time, the efficiency is obviously low. The author provides a method to improve efficiency, mainly using HTTP header information.

When you visit a Web page, the server returns the requested header information, where content-length represents the size of the requested page content. If the request is a picture, then content-length represents the size of the picture. Based on this, just send the head request to get the returned header information OK. In PHP, you can get header information through the Fsockopen method. The code is as follows:

Copy Code code as follows:

$fp = Fsockopen ("www.baidu.com", $errno, $errstr, 30);
if ($fp) {
Here, the request is set to head.
$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 a GET request, just set the request type get to head. The requested host and path, modify it to their own needs on it.

Summary:

PHP can also use Get_headers to get the header information, but the author tested this function, is a GET request, details Reference: PHP function get_headers is a head request or a GET request.

Other servers may block head requests, and if they are blocked, they can only be used honestly with get requests. If you want to do this, you can use the Out-of-the-box function getimagesize directly.

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.