繁体   English   中英

使用PHP imagecreatefromstring时如何从第三方网站捕获无效图像

[英]How to catch invalid image from third party website when using 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;
    }
}

提供的脚本对我来说很好用,对其进行调试以检查curl错误:

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对其进行了测试,它工作正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM