2013-06-24 101 views
1

对不起再次提问,但我真的需要帮助。我在包含header_sub.php的根目录/ lib中包含header.php。在根文件通常可以直接包括他们这段代码:更改工作目录

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不会正确包含。

有没有办法在不修改它们的情况下包含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(),它仍包括这根/博客/ lib目录后根目录......

+0

你应该尝试保持一致并且有一个可以访问这些文件的共同路径。创造黑客来阅读糟糕的设计并不是一个解决方案。 – DevZer0

+0

是'/ lib'的'/ blog'子目录吗? – Sergio

+0

嗨塞尔吉奥,不,它不是,他们都是根 – Andrew

回答

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”的文件是你为某些文件夹定义路径。如果您的网站目录有许多子文件夹,这很有用。