I am getting a image source from a URL dynamically, but sometimes the URL returns empty or the image does not exist so i created a PHP
function to check if the image source do exist or not so i can display a default image to my users when the image is not accessible.
My concern, is my function enough to catch the data?
My current php function which works when its sure that a image do exist.
function get_image_by_id($ID) {
$url = 'http://proweb/process/img/'.$ID.'.jpg';
if(empty($url)){
return 'default.jpg';
}else{
return $url;
}
}
My index.php
<img src="<?php echo get_image_by_id($ID);?>" />
You can use php is_file()
to determine.
if (is_file($url) {
//its a file
}
You can use a ternary operator(one liner)
return is_file($url) ? $url : 'default.jpg';
Here CURL
can also be helpful, tested it and working fine. Here we are using curl to get HTTP response code for the URL. If status code is 200
it means it exists.
function get_image_by_id($ID)
{
$url = 'http://proweb/process/img/' . $ID . '.jpg';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$info = curl_getinfo($ch);
if ($info["http_code"] != 200)
{
return 'default.jpg';
}
else
{
return $url;
}
}
you can use like this
<?PHP
function get_image_by_id($ID) {
$url = 'http://proweb/process/img/'.$ID.'.jpg';
// Checks to see if the reomte server is running
if(file_get_contents(url) !== NULL)
{
return $url;
}
else
{
return 'default.jpg';
}
}
?>
function get_image_by_id($ID) {
if(empty($url)){
$url = 'http://proweb/process/img/default.jpg;
}else{
$url = 'http://proweb/process/'.$ID.'.jpg';
}
return $url
}
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.