0

On this link I was learning about file_get_contents and I'd like to incorporate it into a simple if/else statement but can't seem to get it correct.

I'd like to check if the file exists and if not, display a no_image.jpg graphic.

My struggle is that the tag already has a PHP echo so it is causing the snippet to stop working. How do I format the if/else while still haveing the use the dynamic value from the echo if file_get_contents is true?

Currently I have a simple tag like this:

<img width="200" height="150" src="images/<?php echo(rawurlencode($row['MLS_NUMBER'])); ?>_1.jpg" alt="" align="left" vspace="3" hspace="3" />

2 Answers 2

6

Basically:

<?php

if (file_exists(...)) {
  $path = ...;
} else {
  $path = 'no_image.jpg';
}
?>

<img src="images/<?php echo $path; ?>" />

//add a semicolon after echo $path otherwise it won't work

Sign up to request clarification or add additional context in comments.

Comments

0

Assuming you are looking for a jpg file based on $row['MLS_NUMBER']

<img width="200" height="150" src="images/
<?php 
 if (file_exists($row['MLS_NUMBER']) {
       echo(rawurlencode($row['MLS_NUMBER'])).'_1.jpg';
     } else {
       echo "no_image.jpg";
     }
 ?>" alt="" align="left" vspace="3" hspace="3" />

3 Comments

How does php know what directory and file extension to looks for with file exists? Don't you need to specify path and .jpg...otherwise it is just looking for the number? I tried this with no luck?
I tried this with no luck? if (file_exists(."/images/".$row['MLS_NUMBER']."_1.jpg"))
@Rocco. The code given is an example. I don't know which jpg you want to show. PHP will NOT know where your graphics are, so you need to add a directory to $row['MLS_NUMBER']. So if for example you have an a graphic named /images/234666234_1.jpg where 234666234 is the MLS number coming in via $row array, then you would write if(file_exists("/images/{$row['MLS_NUMBER']}_1.jpg") etc. Your code may have failed because of the additional . (dot) in the file_exists(."/images line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.