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

There are some instances where you might need to redirect from the page you are on. For example, the user needs to be logged in so whip them away to the login page.

In PHP, this can be done like so:

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

If you do employ this method, don’t forget that the script may continue executing after the user has gone. Always follow up your header redirects with a die();

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

Are you a Developer, Designer or Copy Writer? Or Looking For One?

Click here to see 100s of jobs updated every day that you can complete to earn good money. Also find that programmer, designer or copy writer you have been looking for - advertise and get the best guy for your job - click here to find out more

4 Comments so far

  1. dragonet123 on December 1st, 2008

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

  2. Jim on January 24th, 2009

    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!

  3. agente_naranja on March 2nd, 2009

    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 :)

  4. [...] to Web Development Advice for that tip. No [...]

Leave a Reply

Make $100,000/Month - Every Month!

It Works! We Make Our Customers Millionaires! Act now and get $600 bonus and a Free Money Making Website! - click to get started