Tip of the Week
February 13, 2008 – 6:26 pmDo you use the header() function to redirect users?
<?php header("Location: http://www.example.com"); ?>
Here’s a little tip: use the exit statement right after you redirect.
Why? Imagine this: You have some code that runs after the redirect (the user was redirected because he did not have the correct permissions to view the page), and that code updates the user table to change some sensitive data. Obviously, you wouldn’t want that code to run after the player is redirected, but it could happen.
By using exit immediately after the redirect, you can stop any other code from executing, and make sure that nothing goes wrong!

5 Responses to “Tip of the Week”
Can you please explain “but it could happen”… it happens always or in certain situations?
By Vlad on Feb 14, 2008
Well, it depends on how your code is structured.
If you have something like this:
< ?phpif ($bla == true)
{
header("Location: index.php");
}
//Sensitive code here
?>
Then part of the sensitive code will execute.
But if you have the sensitive code in an else statement, then it won’t:
< ?phpif ($bla == true)
{
header("Location: index.php");
}
else
{
//Sensitive code here
}
?>
Also, I said ‘part of the sensitive code’ because I think it’s different for every server/page/user. I think it depends on how much of the rest of the page is loaded by the server before the user is redirected.
Either way, it’s safest to add exit right after a redirect
By Andy on Feb 14, 2008
Great tip, thanks!
By mobeamer on Feb 14, 2008
vERY USEFUL INFO! tHANKS
By xfx 680i on Feb 19, 2008
Be sure to use exit; after the header redirect.
By Matt Dudley on Aug 18, 2008