【问题标题】:redirection if some variable is missing creates an error saying the variable is missing [duplicate]如果缺少某个变量,则重定向会创建一个错误,指出该变量丢失[重复]
【发布时间】:2021-06-20 06:15:10
【问题描述】:

如果 url 中没有 id,我想从数据库中获取 id,然后使用 id 重定向到同一页面

if(!isset($_GET['id'])){
    $st = $db->query("select id from video where ind = 0 limit 1");
    $st->execute();
    $id = $st->fetchColumn();
    header('location: index.php?id='.$id);
}

$urid = $_GET['id']; // line 15

一切正常,页面被重定向,id 在那里,但系统会创建一个 error.log 文件说:

Undefined array key "id" ... on line 15

那么为什么系统会产生这个错误
重定向应该在line 15之前发生

【问题讨论】:

    标签: php redirect


    【解决方案1】:

    你应该在重定向旁边有exit;

    <?php
        header("Location: http://www.example.com/"); /* Redirect browser */
        
        /* Make sure that code below does not get executed when we redirect. */
        exit;
        ?>
    

    【讨论】:

    • 谢谢,但逻辑是什么?如何在到达之前执行代码。 php 不是异步的,不是吗?
    • 有两个特殊情况的标头调用...一个是location,另一个是HTTP/。对于位置,我们必须使用exit,否则下面的代码将被执行
    • 通常情况下,以前重复回答过的问题不应该回答。副本应提供足够的资源来解释解决方案。如果您觉得可以添加到该问题,请在链接的问题上添加,而不是在此处添加。
    猜你喜欢
    • 2023-03-29
    • 2010-12-24
    • 1970-01-01
    • 2014-08-14
    • 2012-02-25
    • 2012-11-21
    • 2019-01-08
    相关资源
    最近更新 更多