2017-06-11 11 views
0

私は以下の方法で無効な画像をキャッチすることができますが、私の場合はダウンロードタイムアウトをキャッチできません。 私はサードパーティのウェブサイトから画像を取得しようとしていますが、スクリプトには がロードされ続けており、応答がありません。エラーを捕捉する方法は十分ではありませんか? 誰かが無効なファイルを捕捉してタイムアウトをダウンロードするより良い方法をアドバイスできますか?ありがとう!PHPを使用しているときにサードパーティのウェブサイトから無効な画像をキャッチする方法imagecreatefromstring

$url = "https://www.example.com/image.jpeg"; 
if (checkRemoteFile($url)) 
{ 
    $imagefile = $url; 
    $resource = imagecreatefromstring(file_get_contents($imagefile)); 

    if ($resource == true) 
    { 
     echo "Image Good"; 
    } 
    else 
    { 
     echo "Image Bad"; 
    } 
} 
else 
{ 
    echo "Invalid file"; 
} 

function checkRemoteFile($url) 
{ 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL,$url); 
    // don't download content 
    curl_setopt($ch, CURLOPT_NOBODY, 1); 
    curl_setopt($ch, CURLOPT_FAILONERROR, 1); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    if(curl_exec($ch)!==FALSE) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 

答えて

0

提供されたスクリプトは、それがカールエラーをチェックデバッグする、私のために正常に動作します:

function checkRemoteFile($url) 
{ 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL,$url); 
    // don't download content 
    curl_setopt($ch, CURLOPT_NOBODY, 1); 
    curl_setopt($ch, CURLOPT_FAILONERROR, 1); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    $result = curl_exec($ch); 
    if ($result === false) { 
     error_log(curl_error($ch)); 
    } 

    curl_close($ch); 

    return $result !== false; 
} 

これはエラーにあなたが悪い応答またはタイムアウトを取得する任意の時間を記録します。ホストがダウンしている可能性がありますタイムアウトを取得している場合、私はそれをhttps://www.w3schools.com/css/trolltunga.jpgでテストし、正常に動作しました。