Buggy header in php
Today, I got a problem in a php script. I was using header() function in the if-else branching. The code is something like
if(condition1)
{
header(”Location:dummy.php?err=1″);
}
else
{
header(”Location:dummy.php?err=2″);
}
if(condition2)
{
header(”Location:dummy.php?err=3″);
}
else
{
header(”Location:dummy.php?err=4″);
}
a contition may fullfill both condition 1 and 2. But in this case I want to go through the first if clause. I run the script and saw that the final page is dummy.php?err=3. But I supposed to get err=1. The question is why this happened? I found its answer. The first condition is fullfilled and the page is directed to dummy.php?err=1, the script does not exit, rather it run from where it was redirected. Then the second condtion is fullfilled. So the page is redirected again to dummy.php?err=3.
The solution is to use exit() function after each header() function so that the script cannot run further after redirection.
The correct code will be,
if(condition1)
{
header(”Location:dummy.php?err=1″);
exit();
}
else
{
header(”Location:dummy.php?err=2″);
exit();
}
if(condition2)
{
header(”Location:dummy.php?err=3″);
exit();
}
else
{
header(”Location:dummy.php?err=4″);
exit();
}
Tags:header, php header function
