php检查远程图像是否无法显示

时间:2015-06-19 04:44:18

标签: php image url curl file-get-contents

我有一个脚本可以从外部网站获取图像并将其显示在我的网站上。如果外部图像是404或无法显示,我需要显示不同的图像。我尝试了各种方法,但无法找到有效的方法:(

这是一个无法在远程服务器上显示的图像示例(它显示文本错误而不是显示图像)http://image.spreadshirtmedia.com/image-server/v1/compositions/1112876576765766798/views/1,width=1000,height=1000,appearanceId=95/

这是我的代码

$path = "http://image.spreadshirtmedia.com/image-server/v1/compositions/111286798/views/1,width=1000,height=1000,appearanceId=95/t.jpg";

// Load the requested image
$image = imagecreatefromstring(file_get_contents($path.'?'.mt_rand()));

// Send the image
header('Content-type: image/png');


function get_http_response_code($path) {
    $headers = get_headers($path);
    return substr($headers[0], 9, 3);
}
if(get_http_response_code($path) != "404"){
    imagepng($image);
}else{
    imagepng("notfound.png");
}

1 个答案:

答案 0 :(得分:0)

我可以指示curl解决您的问题:

代码示例:

$curlIni = curl_init("http://image.spreadshirtmedia.com/image-server/v1/compositions/111286798/views/1,width=1000,height=1000,appearanceId=95/t.jpg");

curl_setopt($curlIni, CURLOPT_NOBODY, true);
curl_exec($curlIni);
$returnCode = curl_getinfo($curlIni, CURLINFO_HTTP_CODE);
// $returnCode >= 400 -> not found, $returnCode = 200, found.
curl_close($curlIni);