Php uses the fsockopen method to obtain the header information. If an image is requested, the Content-Length indicates the image size. if you want to obtain the size of a remote image, A common practice is to retrieve the content of a remote image and calculate the length using strlen. this method requires downloading the image before calculating it. If the image size is large, network transmission takes a lot of time and the efficiency is obviously low. The author provides a method to improve efficiency, mainly by using http header information.
When you access a webpage, the server returns the header information of the request. Content-Length indicates the size of the requested webpage Content. If an image is requested, Content-Length indicates the image size. Based on this, you only need to send a head request to obtain the returned header information. In php, you can use the fsockopen method to obtain header information. The code is as follows:
The code is as follows:
$ Fp = fsockopen ("www.baidu.com", 80, $ errno, $ errstr, 30 );
If ($ fp ){
// Set the request 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 ";
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 )";
}
Like initiating a GET request, you only need to set the request type "GET" to "HEAD. The requested host and path can be modified as needed.
Summary:
You can also use get_headers in php to obtain the header information. However, I have tested this function and it is a GET request. for details, refer to: whether the php function get_headers is a HEAD request or a GET request.
In addition, some servers may block HEAD Requests. if they are blocked, they can only use GET requests honestly. To do this, you can use the ready-made function getimagesize.