Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the code execute after redirection

Tags:

php

Why the execution goto after redirection using header()

  $flag=1;
  if($flag==1)
      header("Location:page1.php");
  header("Location:page2.php");

when use this code page redirects to page2.php, Why its happen

like image 819
Rajasekar Gunasekaran Avatar asked Jun 25 '11 17:06

Rajasekar Gunasekaran


2 Answers

You need to put an exit; after the header call; PHP does not automatically stop executing code after the client stops loading the page.

like image 143
Amber Avatar answered Sep 25 '22 13:09

Amber


The code should be like:-

$flag=1;
if($flag==1) {
    header("Location:page1.php");
    exit();
}
header("Location:page2.php");
exit();

If you don't use the "exit()" / "die()" construct, PHP will continue to execute the next lines. This is because PHP redirects the user to the first-mentioned page (in this case it's "page1.php"), but internally after executing all the statements written in the whole page, even after the "header()" method is executed. To stop this, we need to use either the "exit()" / "die()" constructs.

Hope it helps.

like image 27
Knowledge Craving Avatar answered Sep 22 '22 13:09

Knowledge Craving