Kamikaza Kamikaza - 1 year ago 127
HTML Question

PHP if image exist in folder show else show default image

I have a store with only 1 product image to see the store inventory, the image name is saved in the folder "product-images" using the same product code when uploading. Example

Adding a new product, the product code is 12345 I chose a image to upload and it get saved in the "product-images" folder as 12345.jpg

Now I show the images in the inventory list like this

<img src="product-images/<?php echo $show['product_code'] ?>.jpg" width="200" height="200">

It works fine but now if the product does not have any image I get the uggly empty image because the file does not exist.

So I want to do something like

if image exist in folder "product-images" show else show image default.jpg

How to check and do this?

Answer Source

you first need to check whether image exists like and then set the value. Something like:

$imagePath = "product-images/".$show['product_code'].".jpg";
    $show['product_code'] = "default";

of course, you need to have one default image in the folder product-images with name default.jpg

but maybe a bit better idea is to do like this:

$imagePath = "product-images/".$show['product_code'].".jpg";
        $imagePath = "product-images/default.jpg";

and then in html put just:

<img src="<?php echo $imagePath ?>" width="200" height="200">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download