即使file_exists()声明文件存在,require()也会失败

Mik*_*ike 4 php include

这是我的代码:

if (file_exists('config.php')) {
    require('config.php'); // This is line 38
}
Run Code Online (Sandbox Code Playgroud)

以某种方式产生错误:

警告:require(config.php)[function.require]:无法打开流:第38行的/path/name/file.php中没有这样的文件或目录

这怎么可能呢?

更新:下面工作:

if (file_exists(getcwd(). '/config.php')) {
     require(getcwd(). '/config.php');
}
Run Code Online (Sandbox Code Playgroud)

Shi*_*dim 6

尝试绝对路径.用dirname(__FILE__).

require(dirname(__FILE__) . '/config.php');
Run Code Online (Sandbox Code Playgroud)

  • 或者只是 ```require( __DIR__ . '/config.php' );``` (2认同)

Ed *_*eal 5

的PHP includerequire以相同的方式操作,并使用一个包括路径(包括).因此,将使用此路径查找文件,如果未正确设置,则不会查看当前目录.

使用get include路径查找此值.


Ein*_*eki 4

尝试忽略包含路径:

if (file_exists('config.php')) {
    require('./config.php'); // This is line 38
}
Run Code Online (Sandbox Code Playgroud)

如果它有效,你就失踪了。目录到包含路径中,您必须选择包含它或使用相对路径文件名

您可以使用 php 配置指令更改 include_path (如果您可以更改 php 配置文件)或在每个文件/项目基础上诉诸get_include_path()set_include_path()

例如:set_include_path('.'. PATH_SEPARATOR . get_include_path());在 php 的第一行(或在公共配置文件中);

资料来源: