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.
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.
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.
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);
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:
It's faster because you've trimmed the network traffic.
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.