John Davidson

php - How can I get it so if an image doesn't display to automatically put in a placeholder

0 comments
Message:


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



My Answer:
You can use the `getimagesize()` function in PHP to check if the image exists before trying to display it. If the image does not exist, you can then display a placeholder image instead.

Here is an example of how you can modify your code to include this check:

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

// Check if the image exists
if (!file_exists($img)) {
$img = 'img/placeholder.jpg'; // Placeholder image path
}

echo 'Image';


In this code snippet, we first set the image path based on your existing conditions. Then, we use the `file_exists()` function to check if the image file exists. If the image does not exist, we set the image path to a placeholder image. Finally, we display the image using an `` tag with the updated image path.

Rate this post

5 of 5 based on 6487 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us