[英]PHP check image if exists and return a text if not
I found this solution, because @getimagesize
was horrible slow: 我找到了这个解决方案,因为
@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;
}
}
It works very fast but this function always tries to load the image even if it isn't exists. 它的运行速度非常快,但是即使该图像不存在,该功能也会始终尝试加载该图像。 Here is how I implement into my code:
这是我实现代码的方法:
<?php if (get_image_by_id($link)): ?>
<?php echo '<img src="' . $link . '" alt="' . $propname . '" />'; ?>
<?php endif; ?>
I need an else only if the image isn't exists then only echo $propname
from the array. 我只需要一个不存在的图像,然后仅从数组中回显
$propname
。
With is_null
it works but it has the same speed as @getimagesize
(slow). 使用
is_null
可以工作,但它的速度与@getimagesize
相同(慢)。
So now the else looks like: 所以现在其他看起来像:
<?php if (is_null(get_image_by_id($link))): ?>
<?php echo $propname; ?>
<?php endif; ?>
How can I make a fast code to this: 我该如何快速编写代码:
if(image_exists($link) {
echo $image;
} else {
echo $propname;
}
Use Curl for returning status to identify existence of image 使用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;
}
?>
You can test to see the curl response and if you have something then do your code: 您可以进行测试以查看卷曲响应,如果有,请执行以下代码:
$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;
}
don't forget to close the curl connection curl_close($ch);
不要忘记关闭curl连接
curl_close($ch);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.