【问题标题】:php Dynamic pagephp动态页面
【发布时间】:2013-01-26 22:31:32
【问题描述】:

我不确定这里的标题是否合适,我的解释可能也一样糟糕,但在这里......我正在使用以下代码生成网页:
来源:Dynamic inclusion in PHP

<?php

$id = $_GET['id']; 

$display = $_GET['display'];
    $displays = array('page1', 'page2', 'page3', 'page4', 'page5&amp;id=$id');

if (!empty($display)) {
        if(in_array($display,$displays)) {
            $display .= '.php';
            include($display);
        }
        else {
        echo 'Page not found. Return to
        <a href="index.php">Index</a>';
        }
    }
    else { //show html

?>

一个典型的页面:

www.website.com/dir/index.php?display=page4

我的问题是:我想将一个页面添加到具有动态值的允许页面数组中。您可以在上面添加的代码中看到我的尝试:'page5&id=$id'

但是当我进入这个页面时:

www.website.com/dir/index.php?display=page5&id=2

我收到错误消息“找不到页面。返回索引”。 (数据库中确实存在值为2的表行id。)

【问题讨论】:

    标签: php url dynamic


    【解决方案1】:

    您应该更好地分别处理 display 和 ID 值。比如这样:

    <?php
    
    $display = $_GET['display'];
    $displays = array('page1', 'page2', 'page3', 'page4', 'page5');
    
    if (!empty($display)) {
            if(in_array($display,$displays)) {
                $display .= '.php';
                include($display);
            }
            else {
            echo 'Page not found. Return to
            <a href="index.php">Index</a>';
            }
        }
        else { //show html
    
    ?>
    

    在 display5.php 中:

     <?php
    
     // some other initializations
    
     $id = $_GET['id'];
     if($id == 2) { // make some special actions for id = 2
    
     // show more html
     ?>
    

    【讨论】:

    • 但是如果 id 的值没有传入 url 怎么用 $_GET['id']; ?还有我用作任意示例的值“2”来表示由用户导航确定的值。
    • 如果您的请求发送至www.website.com/dir/index.php?display=page5&amp;id=2,正如您所写,两个可用的$_GET 变量将是$_GET['display']$_GET['id']。因此 ID 将在您的 sn-p 中传递。包含在那里的每个文件也可以访问 $_GET 变量,因此display5.php 可以访问它。 if($id == 2) { 只是我展示如何处理 ID 的一个例子。您可以在此处执行一些数据库 SELECT 语句,例如
    • 好的,我明白了。但是现在,无论出于何种原因,当我尝试您解释的内容时,即使使用示例中的 url 我也无法使用 $id = $_GET['id'];回声 $id;
    • 确认。有一个错字。现在可以使用了,非常感谢您的帮助!
    【解决方案2】:

    就像您将在$_GET['display'] 中收到一个值一样,您将在$_GET['id'] 中收到另一个,其值为2

    PHP 将它们与查询字符串分开。当您使用in_array() 时,您将检查page5 是否在$displays 中,从您的代码中可以看出,它不是。

    我建议您使用var_dump($_GET);,然后查看生成的 HTML 的源代码,了解如何处理 GET 参数。

    【讨论】:

      【解决方案3】:

      这就是为什么$_GET["display"] 中只有“page5”,$_GET["id"] 中只有 2。您可以在 page5.php 中查看 ID。

      例如在page5中:

      <? if (empty($_GET["id"]) || !is_numeric($_GET["id"])) { die("ID isn't a number!"); } ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-21
        • 2011-11-08
        • 2019-11-07
        • 2011-04-16
        • 2019-07-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多