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

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

问题描述

有没有办法检查文件(带有绝对路径或相对路径)是否存在?我使用 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__),它以 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天全站免登陆