Search code examples
phpfile-existsdocument-root

check file existence from root


I tried the following code to check existence of file in root.

if($res['profile_picture']!="" && file_exists("images/".$res['users_id']."/thumnails/".$res['profile_picture'])){
    $photo_p="images/".$res['users_id']."/thumnails/".$res['profile_picture'];
}

It works only on root directory not sub directory.

I'm not sure whether function file_exist checks for both absolute and relative paths so I tried adding ROOT and $_SERVER['DOCUMENT_ROOT']. But still it didn't worked out.

Any Help?


Solution

  • For code portability I suggest you always use absolute paths in functions like file_exists(), otherwise you may wind up breaking your head when including multiple files in different directories and/or running in CLI mode.

    ROOT constant may be undefined in your code. Also, $_SERVER['DOCUMENT_ROOT'] in some circumstances cannot be relied on, i.e. when you use vhost_alias apache module.

    Generally,

    file_exists("{$_SERVER['DOCUMENT_ROOT']}/images/{$res['users_id']}/thumnails/{$res['profile_picture']}")
    

    should work for you.