Correct PHP way to check if external image exists?

后端 未结 9 1293
清歌不尽
清歌不尽 2021-02-04 08:49

I know that there are at least 10 the same questions with answers but none of them seems to work for me flawlessly. I\'m trying to check if internal or external image exists (is

9条回答
  •  隐瞒了意图╮
    2021-02-04 09:51

    Use fsockopen, connect to the server, send a HEAD request and see what status you get back.

    The only time you need to be aware of problems is if the domain doesn't exist.

    Example code:

    $file = "http://example.com/img.jpg";
    $path = parse_url($file);
    $fp = @fsockopen($path['host'],$path['port']?:80);
    if( !$fp) echo "Failed to connect... Either server is down or host doesn't exist.";
    else {
      fputs($fp,"HEAD ".$file." HTTP/1.0\r\n"
         ."Host: ".$path['host']."\r\n\r\n");
      $firstline = fgets($fp);
      list(,$status,$statustext) = explode(" ",$firstline,3);
      if( $status == 200) echo "OK!";
      else "Status ".$status." ".$statustext."...";
    }
    

提交回复
热议问题