2013-06-24 158 views
0

我在根/ lib中包含header_sub.php在同一目录中的header.php。在根文件通常可以直接包括他们这段代码:包括嵌套的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?

+0

试着把require_once而不是include_once告诉我们你得到了什么错误。 –

回答

0

变化在头文件中的代码使用绝对路径,就像你试图用其它文件,使用要做到:

include_once($_SERVER['DOCUMENT_ROOT'].'/header_sub.php'); 
在你的头文件

,这种方式包括独立于当前文件系统位置,这绝对不是相对的。

好吧,发现应该更好,不需要你修改的header.php适合你另一种解决方案,而只是任何文件包括头

<?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 
?> 

这样做是什么改变了工作目录一秒钟,包括头文件(它将全部与头文件通常使用的工作目录一起编译),然后将工作目录设置回正常以方便以后需要相对包含其他内容。

+0

谢谢亚历克斯这是一个很好的解决方案,但在我的情况下,我有两个相同的网站分别在开发和生活环境,最好不要修改lib目录中的原始文件 – Andrew

+0

好吧,看看我的编辑,添加了一个新的解决方案 –

+0

,这正是我期望的方法,但由于某种原因,它在我的网站上无法正常工作。其实我有这些<?php echo getcwd(); \t \t \t chdir(“../”); \t \t \t echo getcwd(); \t \t \t include_once( 'LIB/emocean-navbar.php'); \t \t \t echo getcwd(); ?>我可以看到echo结果是根目录,但“include_once”仍然包含子目录。这是超级怪异的 – Andrew