php 检查具有绝对和相对路径的文件是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1730547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if files with absolute and relative path exists
提问by uji
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.
有没有办法检查文件(具有绝对路径或相对路径)是否存在?我使用 PHP。我找到了几种方法,但它们要么只接受绝对的,要么接受相对的,但不能同时接受两者。谢谢。
回答by Stepan Mazurov
file_exists($file);does the trick for both relative and absolute paths.
file_exists($file);对相对路径和绝对路径都有效。
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:
然而,更有用的是拥有绝对路径而无需对其进行硬编码。最好的方法是使用dirname(__FILE__)它以以太 UNIX 或 Windows 格式获取当前文件的目录完整路径。然后我们可以使用realpath()which 方便地返回 false 如果文件不存在。然后你所要做的就是从该文件的目录中指定一个相对路径并将它们放在一起:
$path = dirname(__FILE__) . '/include.php';
if (realpath($path)) {
include($path);
}
回答by Gumbo
回答by Rob
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");
file_exists($path)将检查绝对路径或相对于脚本位置。如果您想检查相对于文档根目录,您可以尝试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") );
}

