0

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);?>" />
1
  • Your empty check seems redundant Commented Nov 3, 2017 at 5:13

4 Answers 4

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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';

1 Comment

It does work. Try accessing the URL from the browser and see what it returns
0

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';
        } 
}
?>

Comments

-1
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
}

1 Comment

This answer has a syntax error, no explanation, scope issues, and is poorly formatted. It adds no value to the page. Please delete this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.