从文件读取(需要)


Reading from file (require)

我有这样的东西:https://i.stack.imgur.com/TKLK2.png 和我目前正在处理"admin"文件夹,里面有"admin.php",但问题是我想从那里阅读"core/init.php"。现在我在管理员中有这个.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';
?>

在"include/header.php"中,我有php require_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

我知道我必须添加../但是然后我在我的索引.php页面上收到该错误,该错误必须在没有该错误的情况下运行,因为它不在文件夹中,它仅从包含文件夹运行页眉和页脚。

正如文档所解释的那样:

根据给定的文件路径包含文件,如果未指定,则根据指定的include_path包含文件。

如果定义了路径 - 无论是绝对路径(在Windows上以驱动器号或''开头,在Unix/Linux系统上以/开头)还是相对于当前目录(以.或..开头),则include_path将被完全忽略。

这如何应用于您的代码?

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

require_once './core/init.php'; - include_path无关紧要; 提供的相对路径(core/init.php)附加到当前目录以获取文件的路径;

解决方案是什么?

上述方法在实践中都不起作用。

使用

子目录包含文件的最安全方法是使用魔术常量__DIR__和函数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)所在的目录。

你能尝试使用$_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

根据变量在

header.php HEADER_DIR中定义__FILE____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";