使用PHP的动态导航包括

时间:2015-07-10 13:09:55

标签: php dynamic include nav

我有一个关于如何动态更改要在网页中显示的内容的问题。 我修复了网站的一些部分 - 标题,导航,页脚,启动和侧栏。

我只想根据用户点击的菜单链接更改我网站的中间部分。

以下是我的index.php

代码
<?php
include "/templates/header.php";
include "templates/menu.php";
include "/templates/splash.php";
$action = "index"; 
$disallowed_paths = array('header','menu','splash','bottom_page', 'footer'); 
if (!empty($_GET['action'])) 
{ 
    $tmp_action = basename($_GET['action']); 
       if (!in_array($tmp_action, $disallowed_paths) && file_exists("/content/$tmp_action.php")) 
        $action = $tmp_action; 
} 
include "/content/$action.php";  
include "/templates/bottom_page.php";
include "/templates/footer.php";
?>

我的 menu.php 包含主页关于产品服务登录链接 我只想根据用户点击的内容将 main_index.php 更改为include

请告知此方法是否良好。 或者我应该多次创建类似 index.php 的文件,并按照菜单上的链接包含每个文件

2 个答案:

答案 0 :(得分:0)

你的答案是

  

GET方法

您可以使用get方法

 <ul>
        <li><a href="?page=example_1">example 1</a></li>
        <li><a href="?page=example_2">example 2</a></li>
        <li><a href="?page=example_3">example 3</a></li>
        <li><a href="?page=example_4">example 4</a></li>
</ul>

    After User Clicks on the link 

    <?php 
        if(isset($_GET['page']) && $_GET['page']!=""){
            $page = "";
            switch ($_GET['page']) {
                case 'example_1':
                    $page = "Page_1.php";
                    break;

                case 'example_2':
                    $page = "Page_2.php";
                    break;

                case 'example_3':
                    $page = "Page_3.php";
                    break;

                case 'example_4':
                    $page = "Page_4.php";
                    break;

                default:
                    $page = "any_default_page.php";
                    break;
            }

            include($page);
        }
     ?>

还有其他方法。但这是最简单有效的

答案 1 :(得分:0)

我认为更好的方法是白名单而不是黑名单。

$existing_pages = array('home', 'contact', 'terms-of-service'); 

if(isset($_GET['action'] && in_array($_GET['action'], $existing_pages)
{
    // load action here
} else {
    //show 404 error
}

请注意,您的整体方法并不理想,您可能会看到像LaravelSymphony这样的现代框架,它们具有可以帮助实现的模板系统。

但出于学习目的,这很好:)