Why code runs after redirection

Why doing goto after redirect using header ()

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

when using this code page it is redirected to page2.php, Why is this happening

+4
source share
4 answers

After calling the header, you need to put exit; ; PHP does not automatically stop code execution after the client stops loading the page.

+8
source

The code should look like this: -

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

If you do not use the " exit() " / " die() " construct, PHP will continue to execute the following lines. This is due to the fact that PHP redirects the user to the first page (in this case, " page1.php "), but internally after executing all the statements written on the entire page, even after executing the " header() " method. To stop this, we need to use either the " exit() " / " die() " constructs.

Hope this helps.

+3
source

Here's how it works:

Server side: PHP creates an HTML page to submit. If $flag == 1 , it changes its title to location:page1.php . In each case , since there is no else , it then changes the title to location:page2.php .

The page then goes to your browser , which redirects you.

My advice: just put else before changing the second header.

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

This should prevent a redirect to page2.php. Just remember to put exit () where necessary.

+1
source

All Articles