1

抱歉再次询问,但我真的需要帮助。我在 root/lib 中有 header.php,其中包括同一目录中的 header_sub.php。通常根目录中的文件可以通过以下代码直接包含它们:

include_once('lib/header.php');

但现在我在子目录 /blog 中有 example.php,如果我使用这些

include_once(../'lib/header.php');  or 
include_once($_SERVER['DOCUMENT_ROOT'].'/lib/header.php');  or 
include_once(dirname(__FILE__).'/lib/header.php');

header_sub.php 不会被正确包含。

有没有办法在不修改它们的情况下包含 header.php 和 header_sub.php?

一些机构建议使用这些:

$oldcwd = getcwd(); // Save the old working directory
    chdir("../"); // Moves up a folder, so from /blog to /
    include("header.php"); // Include the file with the working directory as if the header file were being loaded directly, from it's folder
    chdir($oldcwd); // Set the working directory back to before

但是,即使我可以看到当前 url 是 chdir() 之后的根目录,它仍然包含这个 root/blog/lib……

4

1 回答 1

2

您需要的文件的路径取决于您是否正在调用该文件。例子:

/root调用文件中/root->include_once('header.php');
/root调用文件中/root/lib->include_once('lib/header.php');
/root/lib调用文件中/root->include_once('../header.php');
/root/blog调用文件中/root/lib->include_once(../lib/'header.php');
/root/blog/css调用文件中/root/lib->include_once(../../lib/'header.php');

如果您这样做,所有路径都是相对的,您可以更改根文件夹,一切仍然有效。

另一种选择是您有一个名为“common.php”或“include.php”的文件,如果您为某些文件夹定义路径。如果您的站点目录有许多子文件夹,这很有用。

于 2013-06-24T10:37:44.157 回答