Search code examples
phpimagefile-exists

PHP file_exists does not work. It seems to be reversing true and false


While working on my photo gallery I decided it was best to have an alternate file if image that should display doesn't. I've looked on this site, and may others. They all say to use:

$VariableName = "photography/small/2014-09-21-red-1.png";
if (file_exists ($VariableName)) {echo "Yes!!!";}
else {echo "Nooo!!!";}

or

if (file_exists ("photography/small/2014-09-21-red-1.png")) {echo "Yes!!!";}
else {echo "Nooo!!!";}

For some reason, this will not work for me. It does work, but only when file_exists is set to !file_exists, which is saying: "if this file does not exist, display the image that exists (the image I want, not it's replacement)". In other words: this is saying if apple exists, display "orange"; and if apple does not exist, display apple.

I've even placed the generated image link in the search bar (when using !file_exists), and after pressing enter, it brings me to the image. I've made sure that the images are set to 0777 in case that's interfering, but it seems to have no effect. All of the $DataRows variables are connected to a database and I've triple-checked that the file names in photography/small match those in the database table.

Why is this happening?

$URLPath = "http://localhost/~matthew/";
if (file_exists ($URLPath . "photography/small/" . $DataRows["DatePublished"] . "-" . $DataRows["FileName"] . "." . $DataRows["ImageExtension"])) {
 echo '<img src="' . $URLPath . "photography/small/" . $DataRows["DatePublished"] . "-" . $DataRows["FileName"] . "." . $DataRows["ImageExtension"] . '" alt="' . $DataRows["PhotoName"] . '">' . "\n";
}
else {
 echo '<img src="' . $URLPath . 'img/no-image.png" alt="Image Not Here">' . "\n";
}

Thank you very much for the help.


Solution

  • What happens if you change $URLPath from

    $URLPath = "http://localhost/~matthew/";
    

    to

    $URLPath = $_SERVER['DOCUMENT_ROOT'] . "/~matthew/";