[英]PHP check image if exists and return a text if not
我找到了這個解決方案,因為@getimagesize
太慢了:
function get_image_by_id($ID)
{
$url = $ID;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$info = curl_getinfo($ch);
if(file_get_contents($url) == NULL)
{
return NULL;
}
else
{
return $url;
}
}
它的運行速度非常快,但是即使該圖像不存在,該功能也會始終嘗試加載該圖像。 這是我實現代碼的方法:
<?php if (get_image_by_id($link)): ?>
<?php echo '<img src="' . $link . '" alt="' . $propname . '" />'; ?>
<?php endif; ?>
我只需要一個不存在的圖像,然后僅從數組中回顯$propname
。
使用is_null
可以工作,但它的速度與@getimagesize
相同(慢)。
所以現在其他看起來像:
<?php if (is_null(get_image_by_id($link))): ?>
<?php echo $propname; ?>
<?php endif; ?>
我該如何快速編寫代碼:
if(image_exists($link) {
echo $image;
} else {
echo $propname;
}
使用Curl返回狀態以識別圖像的存在
<?php
function image_exist($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code == 200){
$status = true;
}else{
$status = false;
}
curl_close($ch);
return $status;
}
?>
您可以進行測試以查看卷曲響應,如果有,請執行以下代碼:
$output=curl_exec($ch);
if ($output === false || $info['http_code'] != 200) {
//$output = "No cURL data returned for $url [". $info['http_code']. "]";
//if (curl_error($ch))
// $output .= "\n". curl_error($ch);
//}
return null; //or $output
else {
// 'OK' status; format $output data if necessary here:
return $url;
}
不要忘記關閉curl連接curl_close($ch);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.