检查是否存在具有绝对路径和相对路径的文件 [英] Check if files with absolute and relative path exists

查看:167
本文介绍了检查是否存在具有绝对路径和相对路径的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以检查文件(具有绝对路径还是相对路径)是否存在?我正在使用PHP.我发现了几种方法,但是它们要么只接受绝对值,要么接受相对值,但不能同时接受.谢谢.

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($file);为相对路径和绝对路径都起到了作用.

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

然而,更有用的是拥有绝对路径而无需对其进行硬编码.最好的方法是使用dirname(__FILE__),它以ether UNIX或Windows格式获取当前文件的目录的完整路径.然后,我们可以使用 realpath() ,如果文件不存在,则方便地返回false.然后,您要做的就是从该文件的目录中指定一个相对路径,并将它们放在一起:

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

这篇关于检查是否存在具有绝对路径和相对路径的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆