如何使用url变量从索引页中的其他页面加载内容


How to load content from other page in index page with using url variable

我正试图借助索引页面中的url varibale从page1.php、page2.php和page3.php抓取内容。

这是我的索引页代码

<html>
<head>
</head>
<body>
<h1>Hello there></h1>
<ul>
<li><a href="index.php?page=page1.php">page 1</a>page1</li>
<li><a href="index.php?page=page2.php">page 2</a>page2</li>
<li><a href="index.php?page=page3.php">page 3</a>page3</li>
</ul>
<?php
    $page = $_GET['page'];
    $pages = array('page1', 'page2', 'page3');
    if (!empty($page)) {
        if(in_array($page,$pages)) {
            include($page);
        }
        else {
        echo 'Page not found. Return to
        <a href="index.php">index</a>';
        }
    }
    else {
        include('page1.php');
    }
?>
</body>
</html>

索引页面显示未定义的变量$page

您必须使用array('page1.php', 'page2.php', 'page3.php');或避免url和数组中的.php扩展,并在include中使用$page.".php"。同时确保$_GET['page'];设置为

<html>
<head>
</head>
<body>
<h1>Hello there></h1>
<ul>
<li><a href="index.php?page=page1.php">page 1</a>page1</li>
<li><a href="index.php?page=page2.php">page 2</a>page2</li>
<li><a href="index.php?page=page3.php">page 3</a>page3</li>
</ul>
<?php
    $page = isset($_GET['page'])?$_GET['page']:'page1.php';
    $pages = array('page1.php', 'page2.php', 'page3.php');
    if (!empty($page)) {
        if(in_array($page,$pages)) {
            include($page);
        }
        else {
        echo 'Page not found. Return to
        <a href="index.php">index</a>';
        }
    }
    else {
        include('page1.php');
    }
?>
</body>
</html>

我建议使用框架中的路由系统。

除此之外,您的$_GET变量:index.php?page=page1.php返回字符串"page1.php",该字符串在$pages数组中不存在。将.php添加到$pages数组中,您应该可以让它正常工作。

路由系统建议:http://silex.sensiolabs.org/

使用symfonys路由和请求组件。会帮你省去一些头疼的事。

<html>
<head>
</head>
<body>
<h1>Hello there></h1>
<ul>

将page1.php更改为page1因为数组中没有page1.php,只有page1…..

<li><a href="index.php?page=page1">page 1</a>page1</li>
<li><a href="index.php?page=page2">page 2</a>page2</li>
<li><a href="index.php?page=page3">page 3</a>page3</li>
</ul>
<?php

你得到了未定义的索引,因为第一次页面加载$_GET['page']时不存在。你需要检查是否设置了$_GET['page']

if(isset($_GET['page']))
{
    $page = $_GET['page'];
    $pages = array('page1', 'page2', 'page3');
    if (!empty($page)) {
        if(in_array($page,$pages)) {

这里$page只包含page1,page2…其他,所以你需要连接".php"

            include($page.".php");
        }
        else {
        echo 'Page not found. Return to
        <a href="index.php">index</a>';
        }
    }
    else {
        include('page1.php');
    }
}
?>
</body>
</html>