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');
}
?>