0

I'm facing a problem.

I have actually this code:

// Check if image exist for the hotel
$src = '../assets/app/images/hotel-logos/007.jpg';

if(file_exists($src)) {
    $src = $src;
}
else {
    $src = '../assets/app/images/hotel-logos/default.jpg';
}

echo '<center><img src="'.$src.'" width="200"></center>';

This code check for an image existence.

But each time I have the fallback image default.jpg whereas I should have 007.jpg.

I check my path and it works. My 007.jpg image is into the same directory as my default.jpg image.

I already test with if(@getimagesize($src)) { ... }. The same.

Why ?

9
  • 6
    Don't arbitrarily use the YOLO operator (@) which suppresses errors. Instead test the file exists first. Why does this do $src=$src? Check if (!file_exists(...)) Commented Jan 18, 2018 at 20:47
  • 6
    Your $src = $src; doesn't make sense. Commented Jan 18, 2018 at 20:47
  • 5
    $src = $src; ... really? Commented Jan 18, 2018 at 20:47
  • 5
    @tadman I've never heard that deemed the "YOLO operator" until now, and I love it. Commented Jan 18, 2018 at 20:47
  • 2
    Try to use a absolute path, e.g. __dir__ . '/../path/to/image.jpg. Are you sure your are pointing to the right path ? file_exists() use local path, but image's src use "URL" path... not the same. Commented Jan 18, 2018 at 20:49

3 Answers 3

1

Even that your file is placed at some directory, doesn't mean that the current path of the PHP process is the same. Use the absolute path instead:

// Check if image exist for the hotel
$src = '../assets/app/images/hotel-logos/007.jpg';

if(!file_exists(__DIR__.'/'.$src)) {
    $src = '../assets/app/images/hotel-logos/default.jpg';
}

echo '<center><img src="'.$src.'" width="200"></center>';
Sign up to request clarification or add additional context in comments.

3 Comments

I guess __DIR__ will fail into src attribute.
Now, it's better :)
$dir = __DIR__.'../assets/app/images'; echo '<center><img src="'.$dir.(file_exists("$dir/007.jpg") ? "/007" : "/default") .'.jpg" width="200"></center>';
0

I think you are over doing it make it simpler might solve your issue Try This:

<?php
$src = '../assets/app/images/hotel-logos/007.jpg';

if (!file_exists($src)) {
    $src = '../assets/app/images/hotel-logos/default.jpg';
}
echo '<center><img src="'.$src.'" width="200"></center>';

?>

Comments

0

Ok, I get it working by using:

$_SERVER['DOCUMENT_ROOT']


// Check if image exist for the hotel
$src = '../assets/app/images/hotel-logos/007.jpg';

if(!file_exists($_SERVER['DOCUMENT_ROOT'].'/assets/app/images/hotel-logos/007.jpg')) {
    $src = '../assets/app/images/hotel-logos/default.jpg';
}

echo '<center><img src="'.$src.'" width="200"></center>';

Comments

Your Answer

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