结构和链接页面的问题

时间:2014-09-07 00:31:10

标签: php include

我是php的新手。我正在开发一个具有这种结构的网站

root
Index.php
Dir1
  (Files)
 - Page.php
Dir2
  (Files)
Includes
 - Header.php
 - Footer.php
 - Newfile.php
 - Style.css
.htaccess

现在,我的问题是如何将page.php和index.php dinamically链接到所有包含文件。 我一直在使用include()但是我遇到了问题,因为page.php和index.php不在同一个目录中。另外如果header包含newfile.php,它可以在index.php中显示,但不能在page.php中显示。

1 个答案:

答案 0 :(得分:0)

更新:如果您正在使用localhost,我假设您可以访问和更改php.ini - 文件。您可以在那里设置include_path

请参阅http://php.net/manual/en/ini.core.php#ini.include-path

示例#1 Unix include_path

include_path=".:/php/includes"

示例#2 Windows include_path

include_path=".;c:\php\includes"


没有太多的服务器权限,没有使用其他工具,它有点复杂。但这里有一个解决方案,可能还会节省很多时间 在根目录中,为包含路径创建一个文件:

<?php 
    //content of path.php

    $root = $_SERVER["DOCUMENT_ROOT"];

    $path = array();

    $path[]= $root;
    $path[]= $root.'/Dir1';
    $path[]= $root.'/Dir2';
    $path[]= $root.'/Includes';

    //you can add more paths here, for example:
    $path[]= $root.'/NewDir';

    foreach($path AS $key => $value)
    {
        set_include_path(get_include_path() . PATH_SEPARATOR . $value);
    }
?>


然后,在每个其他文件中,您必须在包含之前添加一行:

<?php
    //in every other php file
    require_once $_SERVER["DOCUMENT_ROOT"]."/path.php";
?>

但这是您必须添加的唯一一行,以便能够包含属于您刚刚定义的路径的所有文件。

因此,如果您想在Newfile.php中加入Page.php

<?php
    //Page.php
    require_once $_SERVER["DOCUMENT_ROOT"]."/path.php";

    include "Newfile.php";
?>
相关问题