Correct PHP way to check if external image exists?

后端 未结 9 1295
清歌不尽
清歌不尽 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."...";
    }
    
    0 讨论(0)
  • 2021-02-04 09:51

    I found try catch the best solution for this. It is working fine with me.

    try{
          list($width, $height) = getimagesize($h_image->image_url);
       }
    catch (Exception $e)
        {
        }
    
    0 讨论(0)
  • 2021-02-04 09:52

    You can use the PEAR/HTTP_Request2 Package for this. You can find it here

    Here comes an example. The Example expects that you have installed or downloaded the HTTP_Request2 package properly. It uses the old style socket adapter, not curl.

    <?php
    
    require_once 'HTTP/Request2.php';
    require_once 'HTTP/Request2/Adapter/Socket.php';
    
    $request = new HTTP_Request2 (
        $your_url, 
        HTTP_Request2::METHOD_GET,
        array('adapter' => new HTTP_Request2_Adapter_Socket())
    );
    
    switch($request->send()->getResponseCode()) {
    
        case 404 : 
            echo 'not found';
            break;
    
        case 200 :
            echo 'found';
            break;
    
        default :
            echo 'needs further attention';
    
    }
    
    0 讨论(0)
提交回复
热议问题