Search code examples
phpfile-exists

PHP - if file_exists not working for image


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.


Solution

  • 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