I found this solution, because @getimagesize
was horrible slow:
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.
With is_null
it works but it has the same speed as @getimagesize
(slow).
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
<?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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.