DevChunks

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();

Share:

3 Responses

  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.

More Posts

How to use PHP Type Declarations

PHP has developed into a more strictly typed language in recent years. Type Declarations help with that and are a fairly new addition to PHP,

Iteration

If you have come to JavaScript from a background in Java or C, then you will like the variation on the for loop. It is

Context Object Manipulation

One of the key concepts of JavaScript is the keyword this, which signifies the JavaScript context object. If you write an inner function, you can access

Polymorphic Functions

It is possible to define multiple functions with the same name in JavaScript, and the last one of those that you define will be the