简体   繁体   中英

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 ?

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

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

?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM