Why I have to call 'exit' after redirection through header('Location..') in PHP?
could the code after the header-location call be effectively executed?
Yes, always. The header
is only a line of data asking the browser to redirect. The rest of the page will still be served by PHP and can be looked at by the client by simply preventing the header
command from executing.
That is easy enough to do with a command-line client like wget
, for example, by simply telling it not to follow redirects.
Bottom line: If you don't prevent it, PHP will send out the whole body even after a header
call. That body is fully available to the recipient without any special hacking skills.
If you redirect but you don't die()
/ exit()
the code is always executed and displayed.
Take the following example:
admin.php:
if (authenticationFails)
{
// redirect and don't die
}
// show admin stuff
If you don't make sure to end the execution after the location header every user will gain access.
header()
instructs PHP that a HTTP header should be sent... When the HTTP headers are sent.
And those are not sent immediatly when you write the call to header(), but when it's time to send them (typically, when PHP needs to begin sending the body of the response -- which might be later than you think, when output_buffering
is enabed).
So, if you just call header()
, there is absolutly ne guarantee that the code written after this statement is not executed -- unless you indicate that it must not, by using exit
/die
.
The user can ignore the Location
header if he wants ; but it will not change anything on the fact that the code after the call of header()
might or might not be executed : that matter is server-side.