Header function

I had the following code at the top of a page thinking that it prevented the rest of the page from executing if the condition was met.


if(!$um->isLoggedinUser())
	header('Location: index.php');

Obviously the simple solution would be to add an else clause such as…


if(!$um->isLoggedinUser()){
	header('Location: index.php');
}
else{
//Execute the rest of the page
}

Or another option would be,


if(!$um->isLoggedinUser()){
	header('Location: index.php');
        die();
}

But I was surprised that the header function waited until the end of the page to work. Is that a configuration thing, or just the norm?

Best would be:

<?php
ob_start();
require_once('authentication.class.php');
..
if(!$um->isLoggedinUser()){
    header('Location: index.php'); 
    exit();
}
//rest code goes here....
?>

The header function does nothing more than send an http header. Sending an http header doesn’t, and shouldn’t, make the script stop executing.

php will send the headers as soon as you send some output(text, html etc…), unless output buffering is enabled. That doesn’t mean the browser will immediately read it though. A location header is strictly an advisory to the remote client(browser). The browser doesn’t need to obey if it doesn’t want to.