PHP Header Redirect? Don’t forget to die();

There are some instances where you want to redirect the user away from the current page. For example, the user needs to be logged in, so you want them redirected to the login page.

In PHP, this can be done like so:

header("Location: http://www.mysite.com/login.php");

If you employ this method, remember that the script will continue after the user has gone. Any code underneath this header() call will still be executed.

Therefore, you should always follow up your header redirects with a die(); or exit();

header("Location: http://www.mysite.com/login.php");
exit();

Similar Posts

3 Comments

  1. This cannot be stressed enough…I have seen on many pages where it shows a basic security mechanism (checking a session variable for example) then just shoves a header at the user.

    It took me awhile to figure out from seeing some table updates that weren’t supposed to happen that you need the die if you have *any* code beneath a header() call. You cannot trust that whatever a user submits will not be processed further down the page.

    Great tip!

  2. Just like Jim said, it takes a while to notice you have to add die() after the header(). I also had a lot of problems because I was redirecting people when a database query returned an error, something like:

    $mysql_query_resource = mysql_query(…);
    if( mysql_error($mysql_resource) ){
    header(‘location:error.php’);
    }

    mysql_fetch_assoc($mysql_query_resource);

    Obviously if you don’t add die() then the call to mysql_fetch_assoc() would be executed with an invalid parameter, it was a pain in the ass until I learned I had to die().

    Thanks for the post 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *