如何正确要求另一个目录中的文件?

时间:2016-07-21 04:00:09

标签: php

在第3行中,我使用以下内容:

require'./inc/connection.php' or die ("Cannot find the proper configuration    file."); 

我收到此错误:

PHP Warning:  require_once(1): failed to open stream: No such file or directory in (directory)

如果有人可以提供帮助,我就是这样设置的。

index.php is the file that is using the require. connection.php is in the "inc" directory.

4 个答案:

答案 0 :(得分:1)

你也可以这样做,以防你在移动源代码时路径发生变化。

$basePath = "/systemdir";
$incPath  = $basePath."/inc/";
require $incPath.'connection.php' or die ("Cannot find the proper configuration file.");

require $incPath.'connection.php';

你真的不需要在最后检查死机,如果在该目录中找不到该文件,php将自动显示错误。

如果您使用的是Windows,请尝试

require __DIR__ . '/connection.php';

require 'inc/connection.php';

答案 1 :(得分:1)

当您包含文件时,您可以:

1-指定该文件的完整路径(以/开头)

例如

require '/var/www/html/site-name/site/lib/inc/connection.php' or die ("Cannot find the proper configuration    file.");

请注意/var/www/site-name/site/lib/部分?这个例子弥补了这一点。真正的绝对路径取决于服务器以及所需文件夹所在的位置。

2-指定该文件的相对路径(以文件夹或文件名开头)

例如

require '../inc/connection.php' or die ("Cannot find the proper configuration    file.");

使用相对路径意味着您从代码实际存在的文件夹开始。例如,路径:'connection.php'表示connection.php位于同一当前文件夹中。

特殊名称...分别表示当前和父目录/文件夹。因此,要包含一个名为connection.php的文件,该文件位于调用它的代码所在的父文件夹中,您可以通过../connection.php将其作为目标。

因此,为了解决您的问题,您需要确定您尝试定位相对的特定文件的位置。看起来当前路径以.开头,这意味着当前文件夹(没有意义)。

一个简单的猜测是它应该是..而不是.,但不一定是这种情况。自该代码实施以来,文件可能已被移动,或者inc名称等文件夹已更改。

答案 2 :(得分:0)

在/ inc

之前放两个点(..)

如下所示。使用此代码代替您的。

require '../inc/connection.php' or die ("Cannot find the proper configuration    file."); 

答案 3 :(得分:0)

当你想要遍历一个目录时,你需要放两个点。你在同一个目录中有index.phpinc所以你应该写

require 'inc/connection.php' or die ("Cannot find the proper configuration file.");