Search code examples
phpfile-exists

Can't make the file_exists function work in PHP


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 ?


Solution

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