Home >Backend Development >PHP Tutorial >PHP uses request header information to obtain the remote image size

PHP uses request header information to obtain the remote image size

WBOY
WBOYOriginal
2016-07-25 08:55:121013browse
  1. $fp = fsockopen("www.baidu.com", 80, $errno, $errstr, 30);
  2. if ($fp) {
  3. //Just set the request to HEAD here.
  4. $out = "HEAD /img/baidu_sylogo1.gif HTTP/1.1rn";
  5. $out .= "Host: www.baidu.comrn";
  6. $out .= "Connection: Closernrn";
  7. fwrite($fp , $out);
  8. while (!feof($fp)) {
  9. $header = fgets($fp);
  10. if (stripos($header, 'Content-Length') !== false) {
  11. $size = trim(substr($header, strpos($header, ':') + 1));
  12. echo $size;
  13. }
  14. }
  15. fclose($fp);
  16. } else {
  17. echo "$errstr ($errno) ";
  18. }
Copy the code

The same as initiating a GET request, just set the request type GET to HEAD. Just modify the requested host and path to what you need.

Summary: PHP can also use get_headers to obtain header information. After testing this function, it is a GET request. For details, please refer to: php function get_headers is a HEAD request or GET request . In addition, some servers may block HEAD requests. If blocked, you can only use GET requests.

In this way, you can directly use the ready-made function getimagesize to get the size of the image.



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