将php文件包含到网站页面中


Including php files into a site page

我正在尝试包含我的header.php&footer.php我在每个页面中创建的文件。到目前为止,它一直在起作用!

一旦我创建了一个新目录,例如/new site area,当我创建了新的php页面并试图包含header.php时,这就不起作用了?

这是我正在使用的php include,它正在工作。。。

<?php include ("includes/header.php");?>

当我试图将它包含到/目录中的页面中时,它似乎就停止了工作。

示例:

www.mysite.com-标题包含作品
www.mysite.com/new-directory/new-area-标头include不起作用

我不明白为什么它会在我的网站根上工作,然而,当页面在我网站的另一个区域时就不会了。

如果这是一个无法解决的问题,请有人建议一种更好的方法,将php文件包含到网站页面中

谢谢!

您必须使用返回参数"../"浏览到您的目录

例如,您的页面

www.mysite.com/new-directory/

应使用

<?php include ("../includes/header.php");?>

对于像这样的2级文件夹

www.mysite.com/new-directory/new-directory2

应该是

<?php include ("../../includes/header.php");?>

尝试include "../includes/header.php"-最好是编写一些包含它的函数,例如:

function load($file) {
    return $_SERVER['DOCUMENT_ROOT']."/includes/$file";
}

然后只使用include(load("header.php"));

或者,如果你想让你的load()函数支持多条路径,可以试试这样的方法:

function load($file) {
    $paths = array(
        "includes",
        "some_other_dir/includes"
    );
    foreach($paths as $path) {
        if(file_exists($_SERVER['DOCUMENT_ROOT']."/$path/$file")) {
            return $_SERVER['DOCUMENT_ROOT']."/$path/$file";
        }
    }
    trigger_error("File $file not found in any of paths", E_USER_ERROR);
}

然后,如果文件位于指定的任何路径中,它将通过include(load("file.php"));包含,如果文件不存在,它将引发错误。

如果不想实现解析include路径的方法,请使用框架。有很多小框架可以处理这个问题和许多其他问题。