开发者

Check if files with absolute and relative path exists

开发者 https://www.devze.com 2022-12-11 14:38 出处:网络
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 n开发者_JS百科ot

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 n开发者_JS百科ot both. Thanks.


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

What's more useful, however, is having absolute paths without hardcoding it. The best way to do that is use dirname(__FILE__) which gets the directory's full path of the current file in ether UNIX or Windows format. Then we can use realpath() which conveniently returns false if file does not exist. All you have to do then 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);
}


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
}


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

精彩评论

暂无评论...
验证码 换一张
取 消