Why the code execute after redirection
Why the execution goto after redirection using header()
$flag=1;
if($flag==1)
heade开发者_JAVA百科r("Location:page1.php");
header("Location:page2.php");
when use this code page redirects to page2.php, Why its happen
You need to put an exit;
after the header call; PHP does not automatically stop executing code after the client stops loading the page.
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.
Here is how it works:
Server side: PHP creates a HTML page to send. If $flag == 1
, it changes its header to location:page1.php
. In every case because there is no else
, it then changes the header to location:page2.php
.
Then, the page is sent to your brower, which redirects you.
My advice: simply put else
before your second header change.
$flag=1;
if($flag==1)
{
header("Location:page1.php");
exit();
}
header("Location:page2.php");
This should prevent redirection to page2.php. Just remember to put exit() where it's necessary.
精彩评论