Check It Yeah, It's On

10Mar/110

PHP: Common Header Redirection Mistake

PHP is known as a server side language, so when developers write a header redirect, they might be making a common mistake, thinking that the client is not involved until their PHP script finishes running.

First, let's see a sample redirection header sent using PHP:

<?php
// check if the user is logged in
if (!$loggedIn) {
  // user is not logged in, redirect them out of here!
  header('Location: http://alexng.net');
}

// otherwise, welcome the user
print "Welcome user!";
?>

Can you spot the bad practice?

You should understand that a header() call simply issues a raw HTTP header to the client (user's browser). And that the interpretation of that HTTP header is entirely the job of the client, not the server.

With that in mind, the client may not interpret the HTTP header in time or maybe not even at all! Therefore, even if $loggedIn is false, the PHP script will continue processing. And the "Welcome user!" message might be printed, which is unintended behavior.

So, in order to play things safe, a good practice is to always terminate your script after your header redirection calls.

<?php
// check if the user is logged in
if (!$loggedIn) {
  // user is not logged in, redirect them out of here!
  header('Location: http://alexng.net');
  exit(); // terminate the script here!
}

// otherwise, welcome the user
print "Welcome user!";
?>
Filed under: Code Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.