Redirect to the same page after log out
12,833
Solution 1
Approach 1: In your logout.php file, you need to check if you have a REFERER url from previous page and redirect, if not, redirect to index.php
<?php
session_start();
session_destroy();
if(isset($_SERVER['HTTP_REFERER'])) {
header('Location: '.$_SERVER['HTTP_REFERER']);
} else {
header('Location: index.php');
}
exit;
?>
Approach 2: You can pass a reference to your login page to redirect.
Logout link
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
<a href="logout.php?redirect=<?php echo base64_encode(curPageURL()); ?>">Logout</a>
logout.php file:
<?php
session_start();
session_destroy();
if(isset($_GET['redirect'])) {
header('Location: '.base64_decode($_GET['redirect']));
} else {
header('Location: index.php');
}
?>
Solution 2
How about,
header('Location:'.$_SERVER['HTTP_REFERER']);
In your login.php file:
$BackToMyPage = $_SERVER['HTTP_REFERER'];
if(isset($BackToMyPage)) {
header('Location: '.$BackToMyPage);
} else {
header('Location: index.php'); // default page
}
Comments
-
IT gIrLy GiRl almost 2 years
index.php
<ul class="top"> <?php if(!isset($_SESSION['login_user'])) { ?> <li class="hover"><a href="#" onClick="revealModal('modalPage')">Login</a> </li> <?php } else {?> <li class="hover"><a href="logout.php">Logout</a> Welcome <?php echo $_SESSION['login_user']; ?> </li> <?php } ?> <li><a href="registration.php" class="about">Registration</a> </li> </ul>
logout.php
<?php session_start(); session_destroy(); header('Location:index.php'); exit; ?>
I have my log out button in my every page, so i want that , if an user clicks in log out, he/she should redirect to the same page.. as i ve given the location page index here, but i want to remain in the same page.. any code to redirect to same page ?? Thank you in advance ..