Home > OS >  How can I get it so if an image doesn't display to automatically put in a placeholder
How can I get it so if an image doesn't display to automatically put in a placeholder

Time:12-07

Please note I don't mean if its meant to be there. I mean if an image cannot be found/located.

For example where the first one below, if monoph.png didnt exist is there a way to display a placeholder?

if ($d == 1 && $h >= 1 && $h < 14) $img = 'img/hosts/monophy.png';
else if ($d == 1 && $h >= 14 && $h < 16) $img = 'img/hosts/mon24.jpg';
else if ($d == 1 && $h >= 16 && $h < 18) $img = 'img/hosts/mon46.jpg';
else if ($d == 1 && $h >= 18 && $h < 20) $img = 'img/hosts/mon68.jpg';
else if ($d == 1 && $h >= 20 && $h < 22) $img = 'img/hosts/mon810.jpg';
else if ($d == 1 && $h >= 22 && $h < 24) $img = 'img/hosts/MON1012.png';
else if ($d == 1 && $h >= 19) $img = 'img/hosts/monophy.png';
else if ($d == 2 && $h < 0) $img = 'img/hosts/monophy.png';

CodePudding user response:

You could do this on the server side or the client side or both. On the server side of things, you could use php's file_exists function to check if the file exists before using it.

https://www.php.net/manual/en/function.file-exists.php

On the client side, you can use the img tag one rror attribute to show a fallback image.

jQuery/JavaScript to replace broken images

CodePudding user response:

I have added a few lines to your original code, now if the file does not exist it will fall back to your fallback image.

// First I initialize $img with an empty string
$img = '';

// Your block of code
if ($d == 1 && $h >= 1 && $h < 14) {
    $img = 'img/hosts/monophy.png';
} else if ($d == 1 && $h >= 14 && $h < 16) {
    $img = 'img/hosts/mon24.jpg';
} else if ($d == 1 && $h >= 16 && $h < 18) {
    $img = 'img/hosts/mon46.jpg';
} else if ($d == 1 && $h >= 18 && $h < 20) {
    $img = 'img/hosts/mon68.jpg';
} else if ($d == 1 && $h >= 20 && $h < 22) {
    $img = 'img/hosts/mon810.jpg';
} else if ($d == 1 && $h >= 22 && $h < 24) {
    $img = 'img/hosts/MON1012.png';
} else if ($d == 1 && $h >= 19) {
    $img = 'img/hosts/monophy.png';
} else if ($d == 2 && $h < 0) {
    $img = 'img/hosts/monophy.png';
}

// Finally we check if $img exist otherwise we fallback on your fallback image
$img = file_exists($img) ? $img : 'path/to/your/fallback/image'
  • Related