1

我想制作没有框架的主页,我是否应该在 index.php 上拆分我的设计,使其成为 header.php/footer.php,然后将它们包含在每个页面上?

4

5 回答 5

5

是的,您可以将 index.php 拆分为 header.php/footer.php,然后将它们包含在每个页面上。请注意,您的页面可以不是静态 HTML 而是 php 脚本,以使用一个脚本显示多个页面。
我也建议不要像这样的普通结构

include 'header.php';
//do some stuff
include 'footer.php';

但另一种结构,更有用:

//do some stuff, retrieve all data.
include 'header.php';
include 'page.php'; //include page template
include 'footer.php';
于 2010-03-13T11:05:56.217 回答
2

I suggest you use a framework. Most frameworks (if not all) have simple template systems, so you don't have to repeat code.

于 2010-03-13T12:46:55.603 回答
1

在站点的每个页面中包含内容的建议解决方案的问题是,如果您想包含其他内容,例如侧边栏,则必须更新站点的所有页面。

一个更好的主意是根本没有脚本-页面连接。因此,您不必为每个要显示的页面编写一个 php 文件。相反,使用一个前端控制器文件,大多数使用网站根目录中的 index.php。然后使用 Apache mod_rewrite 或其他服务器技术在您的站点的 URL 中具有灵活性。然后让 index.php 映射不同的 URL 请求来服务不同的页面,然后您可以将您网站的所有页面放入数据库或其他地方。

这样,您的站点中只有一个点包含页眉和页脚的模板,因此很容易更改,并且您可以使用站点的根来处理 AJAX 请求,您不想在其中输出 HTML 而是 JSON例如。

Afaik 这是一个很好的解决方法。

于 2010-03-13T12:29:54.413 回答
0

另一个想法是只有一个使用GET参数调用的单一入口点,例如?site=about。你index.php可能看起来像这样:

<?php
// whitelist of allowed includes
$allowedIncludes = array('home', 'about', 'error404'); // etc.
// what to include if ?site is not set at all / set to an illegal include
$defaultInclude = 'home';
$errorInclude = 'error404';

// if site is not set, include default
$site = (empty($_GET['site'])) ? $defaultInclude : $_GET['site'];
// if site is illegal, include error page
$include = (in_array($site, $allowedIncludes)) ? $site : $errorInclude;

// actual includes
include 'header.php';
include $include.'.php';
include 'footer.php';

因此,您只需要包含一次header.php并且footer.php可以完全控制允许的内容和不允许的内容(包含的文件可能位于只有 php 可以访问的目录中)。在您index.php处理请求时home.phpabout.php不必知道header.phpand footer.php(您可以在以后轻松替换它们)。

如果你不喜欢http://www.example.com/?site=about,你可以看看mod_rewrite和朋友。

于 2010-03-13T12:02:32.323 回答
-1

您可能想为此设置一个会话。只要访问者在您的网站上,会话变量就存在:

<?php
    session_start(); // Remember that session_start(); must be the first line of your PHP and HTML-code

    if($add_a_message){
        $_SESSION['message'] = 'Message';
    }

    if($destroy_message){
        $_SESSION['message'] = '';
    }

    // echo this message
    if(isset($_SESSION['message']) && strlen($_SESSION['message']) > 0){
        echo '<strong>' . $_SESSION['message'] . '</strong>';
    }
?>
于 2010-03-13T10:40:17.057 回答