Check if files with absolute and relative path exists(检查具有绝对和相对路径的文件是否存在)
问题描述
有没有办法检查文件(带有绝对路径或相对路径)是否存在?我使用 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);
}
这篇关于检查具有绝对和相对路径的文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查具有绝对和相对路径的文件是否存在
基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何替换eregi() 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
