简体   繁体   中英

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.

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

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