0

I have API $url which should return image depending on the request. It either returns an image or it doesn't return anything and then I get error Failed to load resource: server responded with a statuf of 404.

Just so you can imagine what I do, I am sending a request with a book ISBN number and API checks if it has a book cover for the ISBN in datatabase and if it does, I get book cover as image returned, but if it doesn't, I want to use my local book icon image instead.

I have tried to do something like this

list($width, $height) = getimagesize($url);
echo "Width: ".$width."<br/>";
echo "Height: ".$height."<br/>";

if($width==1 && $height==1){
   echo "<img src='../images/book_cover.png' alt='' class='cover'/>";
}else{
   echo "<img src=$url alt='' class='cover'/>";
}

But since getimagesize() does not return FALSE, I get php warning message.

Then I tried to use

if(!exif_imagetype($url)){
   echo "<img src='../images/book_cover.png' alt='' class='cover'/>";
}else{
   echo "<img src=$url alt='' class='cover'/>";
}

This works, but I get a warning failed to open stream: HTTP request failed.

Any ideas what will do the trick and make it all legit?

EDIT:

echo "<img src=$url onerror=\"this.onerror=null;this.src='../images/book_cover.png';\" alt='' class='cover'/>";
Ady96
  • 686
  • 4
  • 12
  • 35

1 Answers1

0

You should handle that directly in your html

HTML if image is not found

Otherwise you still can check if url exists with a curl or file_get_contents but this would be slower

jawbonewalk
  • 162
  • 2
  • 9