【问题标题】:Creating links to embed page创建嵌入页面的链接
【发布时间】:2013-11-23 17:31:59
【问题描述】:

我创建了一个 index.php,用作带有内容框的模板。我还有 home.php、about.php 和 contact.php,它们只包含填充该内容框的内容。这是我用来将页面嵌入该内容框的代码:

<?php 
    if(!$_GET[page]){ 
        include "home.php"; // Page to goto if nothing picked 
    } else { 
        include $_GET[page]."php"; // test.php?page=links would read links.php 
    } 
?>

主页工作正常,但我不确定在主菜单中使用什么代码链接到其他页面。我很难得到答案,所以我想我可能用错误的术语搜索,这就是我在这里问的原因。

在网站的主菜单上,我在链接中使用了哪些代码,以便它们获得 home.php、about.php 或 contact.php?

【问题讨论】:

标签: php hyperlink embed


【解决方案1】:
<a href="index.php?page=about">About</a>

?<key>=<value> in the url.

您使用键在 $_GET 数组中查找一个值。

【讨论】:

    【解决方案2】:
    if(!$_GET[page]){ 
        include "home.php"; // Page to goto if nothing picked 
    } else { 
        include $_GET[page].".php"; // test.php?page=links would read links.php 
    } 
    

    只是缺少了“。”在'php'之前。 您应该为数组使用引号,以避免出现通知(未定义的常量)

    但请注意,您应该确认 $_GET['page'] 仅包含您希望使其可访问的网站。否则,攻击者可能只会读取您服务器上的任何文件。

    if(array_key_exists('page', $_GET)) {
        $page = preg_replace('~[^a-z]~', '', $_GET['page']);
        include __DIR__ . '/' . $page . '.php';
    } else {
        include __DIR__ . '/home.php';
    }
    

    更好的解决方案(但您必须手动添加所有页面):

    $page = (array_key_exists('page', $_GET) ? $_GET['page'] : 'home');
    switch($page) {
        case 'about':
        case 'links':
        case 'whatever':
            include __DIR__ . '/' . $page . '.php';
            break;
        default:
            include __DIR__ . '/home.php';
            break;
    }
    

    【讨论】:

      【解决方案3】:

      我做了以下测试:

      $page = "test.php?page=links";
      $link = explode("=", $page);
      echo $link[1].".php"; //gets links.php
      

      因此,您的代码应如下所示:

      <?php 
      if(isset($_GET[page])){ 
           $page = $_GET[page];
           $link = explode("=", $page);
           include $link[1].".php"; // test.php?page=links would read links.php 
      
      } else { 
          include "home.php"; // Page to goto if nothing picked 
          } 
      ?>
      

      感谢。

      【讨论】:

        猜你喜欢
        • 2021-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-03
        • 2017-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多