1

Right, as simple as this is supposed to be, I simply cannot get this code to work. I am trying to check whether a users avatar image exists, and in case it does not, use the default one instead. Now, even though the image exists and filename, path, spelling, format, etc. are correct, file_exists() always returns false claiming that the file does not exist.

 <?php $avatar = 'http://'.$_SERVER['SERVER_NAME'].'/ihg/dist/img/user'.$_SESSION['ID'].'-128x128.jpg'; $default = 'http://'.$_SERVER['SERVER_NAME']."/ihg/dist/img/user_default.jpg"; if (!file_exists($avatar)) { echo "<img src=\"$default\" class=\"user-image\" alt=\"User Image\">"; } else { echo "<img src=\"$avatar\" class=\"user-image\" alt=\"User Image\">"; } ?> 

Is this a server side issue or is the code faulty?

EDIT: I also tried using the $_SERVER['DOCUMENT_ROOT'] variable and absolute paths, but no result.

1
  • Why does the default use double-quotes instead of singles after the server variable? Anyway, could it be a folder permissions issue? Commented Jan 21, 2017 at 4:48

1 Answer 1

3

file_exists() accepts a file path rather than a URL.

To determine whether an image exists based on a URL you need to check the response type instead.

Since these are local resources you simply need to switch from using a URL to the full server file path. ($avatar = '/path/to/root/...)

http://php.net/manual/en/function.file-exists.php

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

3 Comments

The problem with that solution is that the image is part of my navigation bar, which is present throught different locations on my server, hence need the dynamic $_SERVER['DOCUMENT_ROOT'] path to always address the same folder. Problem is, the document_root doesnt seem to work either...
Have you tried outputting $_SERVER['DOCUMENT_ROOT'] and verifying you're getting the location you expect / calculating the path accordingly?
just did and found the problem :) I was missing a / after the $_SERVER['DODUCMENT_ROOT'], things are working fine now. THANKS!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.