1

if there is no id in url I want to get the id from database and then redirect to the same page using the 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

everything works, page is redirected and id is there but the system creates an error.log file saying:

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

so why the system creates this error
redirection should happens before line 15

qadenza
  • 9,025
  • 18
  • 73
  • 126

1 Answers1

2

you should have exit; next to the redirect

<?php
    header("Location: http://www.example.com/"); /* Redirect browser */
    
    /* Make sure that code below does not get executed when we redirect. */
    exit;
    ?>
Indra Kumar S
  • 2,818
  • 2
  • 16
  • 27
  • it works thanks, but what is the logic? how the code can be executed before it is reached. php is not async, isn't it? – qadenza Jun 20 '21 at 06:28
  • There are two special-case header calls... one is `location` and another is `HTTP/`. For location, we must use exit, otherwise the code below will get executed – Indra Kumar S Jun 20 '21 at 06:47
  • Normally, questions that have been answered repeatedly before shouldn't be answered. The duplicate should provide enough resources to explain the solution. If you feel as though you can add to that question, then do so on the linked question and not here. – Nigel Ren Jun 20 '21 at 07:07