从文件中读取(需要)

Reading from file (require)

我有这样的东西:http://i.imgur.com/KPulyBg.png,我目前正在处理 "admin" 文件夹,里面有 "admin.php",但问题是我想阅读 "core/init.php" 从那里。现在我在 admin.php

中有了这个
<?php
require '../includes/header.php';
?>

<?php
$user = new User();
if(!$user->isLoggedIn()){
    Redirect::to(404);
}
else if(!$user->hasPermission('admin')){
    Redirect::to(404);
}
?>
<div id="content">

</div>

<?php
require '../includes/footer.php';
?>

在"includes/header.php"里面我有phprequire_once'core/init.php';但我在我的管理页面上得到了这个:

Warning: require(core/init.php): failed to open stream: No such file or directory in C:\xampp\htdocs\OOP\includes\header.php on line 2

Fatal error: require(): Failed opening required 'core/init.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\OOP\includes\header.php on line 2

我知道我必须添加 ../ 但后来我在我的 index.php 页面上得到了那个错误,它必须是 运行 没有它,因为它不在文件夹中,它只是 运行包含文件夹中的页眉和页脚。

根据 __FILE__ 变量在 header.php HEADER_DIR 中定义。其中 __FILE__ 是 php 的魔法常量之一,请参阅此处了解更多信息:http://php.net/manual/en/language.constants.predefined.php

define('HEADER_DIR', dirname(__FILE__)); 

// then use it in all includes 
require HEADER_DIR . "/../core/init.php";
require HEADER_DIR . "../some_other_folder/some_file.php";

您可以尝试使用 $_SERVER["DOCUMENT_ROOT"] 而不是 "../" 我认为这将解决您的问题需要手术。

<?php
require ($_SERVER["DOCUMENT_ROOT"].'/includes/header.php');
?>

<?php
$user = new User();
if(!$user->isLoggedIn()){
    Redirect::to(404);
}
else if(!$user->hasPermission('admin')){
    Redirect::to(404);
}
?>
<div id="content">

</div>

<?php
require ($_SERVER["DOCUMENT_ROOT"].'/includes/footer.php');
?>

您可以在此处找到有关 DOCUMENT_ROOT 密钥的参考:http://php.net/manual/en/reserved.variables.server.php

正如 documentation 解释的那样:

Files are included based on the file path given or, if none is given, the include_path specified.

...

If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include_path will be ignored altogether.

这如何适用于您的代码?

require_once 'core/init.php'; - PHP 搜索来自 php.ini 指令的所有路径 include_path。它将 core/init.php 附加到列表中的每个路径,并检查以这种方式计算的路径是否存在。很可能不是。

require_once './core/init.php'; - include_path 无所谓;提供的相对路径(core/init.php)追加到当前目录,得到文件的路径;

有什么解决办法?

None 以上方法在实践中确实有效。

使用子目录包含文件的最安全方法是使用魔术常数 __DIR__ and the function dirname() 计算正确的文件路径。

require '../includes/header.php';

变成

require dirname(__DIR__).'/includes/header.php';

require_once 'core/init.php';

变成

require_once dirname(__DIR__).'/core/init.php';

因为__DIR__是当前文件(includes/header.php)所在的目录