tags:

views:

570

answers:

3

Is there a way to check whether files (with either an absolute or relative path) exists? Im using PHP. I found a couple of method but either they only accept absolute or relative but not both. Thanks.

A: 

file_exists($path) will check absolute path or relative to the script location. If you want to check relative to document root you could try file_exists("{$_SERVER['DOCUMENT_ROOT']}path");

If you want a function that will take both relative and absolute paths something like this should work (untested):

function check_file($path) {
    return ( file_exists($path) || file_exists("{$_SERVER['DOCUMENT_ROOT']}path") );
}
Rob
+5  A: 

file_exists($file); does the trick for both relative and absolute paths.

Whats more useful, however is having absolute paths without hardcoding it. Best way to do that is use dirname(__FILE__) which gets the directory's full path of the current file in ether unix of windows format. Then we use realpath() which conviniently returns false if file does not exist. All you have to do is specify a relative path from that file's directory and put it all together:

$path = dirname(__FILE__) . '/include.php';
if (realpath($path)) {
    include($path);
}
smazurov
+2  A: 

You can use realpath to check if a file exists to the given path and retrieve the expanded path to that file:

$absPath = realpath($path);
if ($absPath === false) {
    // invalid path
}
Gumbo