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.
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") );
}
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);
}