更改工作目录

时间:2013-06-24 08:24:03

标签: php url directory

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

include_once('lib/header.php');

但现在我在子目录/博客中有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将无法正确包含。<​​/ p>

有没有办法在不修改它们的情况下包含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 ......

1 个答案:

答案 0 :(得分:2)

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

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

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

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

相关问题