Jump to content

Show Image If It Exists Else..


TKO

Recommended Posts

Hello i am tring to show $image1 if it exists and if not show $image2

This script shows $image1 but if i erase the image it just shows a broken image icon and doesnt go to $image2

any help in this would be great

 

<?php
   $image0 = $_SESSION['ls_user'];
   $image1 = "<img src=img/$image0.png>";
   $image2 = "<img src=img/default.png>";
   if ( $image1 ) {
   echo $image1;
   } else {
   echo $image2;
   }
?>

 

thank you

Link to comment
Share on other sites

thanks for the reply

now the code only shows $image2

<?php
   $image0 = $_SESSION['ls_user'];
   $image1 = "<img src=img/$image0.png>";
   $image2 = "<img src=img/default.png>";
   if (file_exists( $image1 )) {
   echo $image1;
   } else {
   echo $image2;
   }
?>

Link to comment
Share on other sites

You need to use an actual path to the image. Also, to check if it exists and that it's an image all in one, you can do if (getimagesize($fn)) and it works well. (: It may be possible that some image filetypes ain't supported by it though, but all the common ones are.

 

Also, you should put {} around your variables when in a string, but you don't need to use the quotes there so it would make more sense to just echo the var.

 

PS: $fn or filename would be the path to it such as /var/www/images/mypic.jpg or if you're in /var/www already you could just do ./images/mypic.jpg but you don't use an HTML image tag.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.