//_Semicolon;

Will code for food; The ramblings of Talifhani Luvhengo;

header() & exit(). BFFs

The PHP header(“Location: /”) function sends a redirect header to the browser. So thing about PHP is that it only sends headers to the browser once the page is parsed on the server. header(); will not stop the execution of code that comes after it. The script will continue to execute until it reaches the end. At which point it will then redirect.

Take this example

//Do stuff
//redirect to another page
if($user_loggedin){
    header("Location:  /login.php");
}
$_SESSION['page_views'] += 1;
/*
Display this page's content
*/

Although its quite clear to a human that if this user is not logged in, we should redirect to login.php, this script will actually continue to execute to the end and then redirect. which means although the page is never really viewed. it will still increment the $_SESSION[‘page_views’] variable.

So the headers are only sent back to the browser once PHP has completed rendering/building the page. At which point the browser redirects to the login.php. So to get the desired effect all you have to do is add a exit() function to stop script execution and force PHP to send the page to the browser as is.

So the code will now look like this:

//Do stuff
//redirect to another page
if($user_loggedin){
    header("Location:  /login.php");
    //stop executing the script
    exit();
}
$_SESSION['page_views'] += 1;
/*
Display this page's content
*/

What I do is just write a function to do both steps like this:

function redirect($url){
        header("Location: $url");
        exit();
}

usage:

redirect("/login.php");
Get Adobe Flash player

Page optimized by WP Minify WordPress Plugin