The header function may seem relatively straightforward on the surface. You issue the function along with a header as the first argument and it does the rest for you. Many people rely religiously on the header function working to forward users to the next page.
To exemplify this, as a programmer you may code the following lines to be placed into your script:
PHP Code:
if($pMember->doLogin())
{
header('location: http://www.talkphp.com/login/success/');
}
$pMember->doLogout();
This will login a user if the login is available, otherwise if the
doLogin returns false or NULL then it logs the user out. Now, this will work absolutely perfectly if everything goes the way you expect it to. The user is logged in and then forwarded to a page where you can praise them for valid credentials.
However, what if the user is logged in and then logged out straight after? It may seem impossible based on the above code as the
header() has been issued to send users to another page before we get down to the
doLogout() function.
This is where paying attention may save the integrity of you as a programmer. Or a blossoming programmer in the very least. The header function is a header instruction sent to the client's browser. It is entirely up to the browser whether or not to act on that instruction. In the simplest terms, the browser makes up its own mind whether or not to follow the location to your desired destination.
What would happen if the browser is stubborn and decides not to exit when the location header is issued? That's right! The script will continue executing causing many adverse effects. In our case logging a user out straight after they've logged in may be an annoyance, but at least it doesn't cause any blatant security issues. However, many programmers rely on the header to protect their scripts.
The security issues arise when you realise how many programmers use location to divert users away from code which should not be executed. To exemplify, the following is a good example of where location is used to divert users away from the page if they are accessing it directly and not via another page that includes this page:
PHP Code:
if(!isset($bUsingSSI))
{
header('location: http://www.talkphp.com/');
}
Please see the attachment for this in action. I have emulated the scenario using Telnet as my browser. Telnet is not going to follow any location unless I explicitly instruct it to.
The lesson to be learned today?
ALWAYS issue the
exit construct after any
header(). Like so:
PHP Code:
if($pMember->doLogin())
{
header('location: http://www.talkphp.com/login/success/');
exit;
}
$pMember->doLogout();
There is then absolutely no way a user will be logged out if they have been logged in a couple of lines above.