【问题标题】:switch $_GET variable else statementswitch $_GET 变量 else 语句
【发布时间】:2016-09-06 15:10:04
【问题描述】:

我遇到了一个问题。如果可能的话,我可以为 $_GET['topic'] 写一个 else 语句吗?

case 'thread-view':
        if(isset($_GET['topic'])){
        $topicid = $_GET['topic'];

        $psql = "SELECT * FROM posts WHERE th_p_link='$topicid' ORDER BY p_id ASC";
        $presult = mysqli_query($db,$psql);
        while($prow = mysqli_fetch_array($presult)){

            $post = $prow['p_post'];
            $author = $prow['p_author'];
            $avatar = $prow['p_avatar'];
            $gm = $prow['p_gm'];
            $date = $prow['p_date'];
            $link = $prow['th_p_link'];

        echo '
        <div class="post_box">
            <div id="post-left">
                <img src="'.$avatar.'" alt="">
                <div id="post-about">
                    <span>'.$author.'</span>
                    <span>Member</span>
                </div>
            </div>
            <div id="post-content">
            <p>'.htmlspecialchars($post, ENT_QUOTES).'</p>
            </div>
            <div id="post-right">
            <i>'.$date.'</i>
            </div>
        </div>
        ';
        }
        }
    break;

    default:
    include 'template/forum_categories.php';

例如,如果我转到 URL

forums.php?page=thread-view&topic=testurlpost

它正确显示了页面。虽然我想要实现的是,如果我去一些不存在的东西,比如

forums.php?page=thread-view&topic=testurlthatdoesntexist

我希望它重定向到另一个页面,例如错误页面。我将如何实现这一目标?我为 $_GET['topic'] 做了一个 else 语句,但是当我输入不存在的 URL 时它不起作用。

【问题讨论】:

  • /forums.php?topic=';%20DROP%20TABLE%20posts;%20--
  • 是否有错误,这就是它不起作用的原因?你检查你的错误日志了吗?
  • 查询后,检查结果行,如果有零行,比id不存在,所以你可以使用header('Location:xy.php');exit;重定向
  • 您也完全对 sql 注入开放,假设 $_GET['topic'] 是 = 类似于 "'; SELECT * FROM posts WHERE 1--" 或更糟糕的 "'; DROP TABLE posts --" 我建议使用准备好的语句重写查询...php.net/manual/en/mysqli.quickstart.prepared-statements.php
  • @ArtisticPhoenix 感谢您告诉我。我从来不知道。所以,对于 $_GET,我应该使用准备好的语句。我可以将 mysqli_real_escape_string 用于 $_POST 变量吗?

标签: php


【解决方案1】:

你应该添加

   if(!mysqli_num_rows($presult)) {
       header("Location: /error-page.html");
    }

在 While 语句之前。所以你的代码看起来像这样:

case 'thread-view':
    if(isset($_GET['topic'])){
    $topicid = $_GET['topic'];

    $psql = "SELECT * FROM posts WHERE th_p_link='$topicid' ORDER BY p_id ASC";
    $presult = mysqli_query($db,$psql);

    if(!mysqli_num_rows($presult)) {
       header("Location: /error-page.html");
    }

    while($prow = mysqli_fetch_array($presult)){

【讨论】:

  • 谢谢!我完全忘记了 mysqli_num_rows 函数
猜你喜欢
  • 1970-01-01
  • 2013-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多