tags:

views:

156

answers:

4

How do you redirect a page back to the home page using PHP when a person signs out. I know there is multiple ways to redirect a page with PHP, but what is the best way?

If you can please leave a code sample. Thanks.

+2  A: 
header('Location: http://www.example.com/');

PHP will magically set the HTTP response code to 302 for you when you issue this header function. Make sure you have not written any output to the client before calling this method or it will fail.

Asaph
+4  A: 
function redirect($url) {
    if (!headers_sent()) {
        //If headers not sent yet... then do php redirect
        header('Location: '.$url);
        exit;
    } else {
        //If headers are sent... do javascript redirect... if javascript disabled, do html redirect.
        echo '<script type="text/javascript">';
        echo 'window.location.href="'.$url.'";';
        echo '</script>';
        echo '<noscript>';
        echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
        echo '</noscript>';
        exit;
    }
}

$url = "www.google.com";
redirect($url);
Phill Pafford
Is all this really necessary? If the server script is processing a log out request after it's creating the next page … sounds more like this is how to handle bad coding rather than designing it correctly the first time.
Nerdling
is it really bad coding to be prepared? Sure it makes sense to only use the header() but what if others are using your code and they echo/print out something before the header? it's just a function that copes with these kinds of situations.
Phill Pafford
+5  A: 

You can use the header() function. You should probably exit your script after.

header('Location: http://www.example.com/');
exit;

Technically your URL should start from "http://" but most browsers (all the big ones) will accept relative urls.

Greg
It's good to put the exit after the header(). Because a user-agent doesn't have to respect the re-direct. (i.e. bot or spider)
null
...and PHP will happily continue processing the rest of the script even though the user already got the redirect header.
Mike B
A: 

If the logout script is actually very simple, the easiest way is to not even redirect. The examples here do work, just fine, but you can also simply do something like:

session_destroy();
include('index.php');

Presuming that the logout and main page are in the same directory. The advantage of this is actually in a couple of ways:

  1. It's faster because you've trimmed the network traffic.

  2. It deals with clients that don't redirect.

Okay, there's the third... You have the opportunity to supply a message to the user about the logout.

There is a downside, however... The user will be sitting on 'logout.php' afterwards. That may not be an issue, but something to be aware of.

John Cavan