Reading from file (require)

半腔热情 提交于 2019-12-02 09:43:36

As the documentation explains:

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.

How this applies to your code?

require_once 'core/init.php'; - PHP searches all the paths from the php.ini directive include_path. It appends core/init.php to each path from the list and checks if the path computed this way exists. Most probably it doesn't.

require_once './core/init.php'; - include_path doesn't matter; the provided relative path (core/init.php) is appended to the current directory to get the path of the file;

What's the solution?

None of the above ways actually works in practice.

The safest method to include files using subdirectories is to use the magic constant __DIR__ and the function dirname() to compute the correct file path.

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

becomes

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

and

require_once 'core/init.php';

becomes

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

because __DIR__ is the directory where the current file (includes/header.php) is located.

Can you try to use $_SERVER["DOCUMENT_ROOT"] instead of "../" I think that will solve your issue about require operation.

<?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');
?>

You can find reference about DOCUMENT_ROOT key here: http://php.net/manual/en/reserved.variables.server.php

Define in your header.php HEADER_DIR based on __FILE__ variable. Where __FILE__ is one of php's magic constants see here for more info: 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";
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!