To avoid browser back button after logout:
You Have To Add the top of each page, to check if the user is logged
in. If not, they should be redirected to a login page:
Example:
<?php
if(!isset($_SESSION['username']) && !isset($_SESSION['useremail'])){
header("Location: login.php"); // redirect to login page or index page if email and username is not set in session
}
?>
Now on Logout page, Simply unset the username
and useremail
session variable, and destroy the session or ( Cookies). what you set.
Example:
<?php
if(isset($_GET['logout'])) {
session_start();
session_destroy();
unset($_SESSION["username"]);
unset($_SESSION["useremail"]);
header('Location: index.php');
exit;
}
?>
Working CODE For All Pages After User Login: Home.php
about.php
contact.php
etc..
Example:
<?php
// After User Login and come to home page.
require 'database_conn.php'; // Connection
session_start(); // Session start
?>
<?php
// If User is Not Login Then Redirect to `index` Page Automatically
//if(!isset($_SESSION['username']) && !isset($_SESSION['useremail']))
if(!isset($_SESSION['useremail'])){
header("Location: index.php");
// Redirect to index page if email is not set in session
}
?>
Working CODE For to Logout User: Logout.php
Example:
<?php
// After User Click On Logout page.
require 'database_conn.php'; // Connection
session_start(); // Session start
?>
<?php
if(isset($_POST['logout'])) {
if(isset($_SESSION['useremail'])){
unset($_SESSION["useremail"]);
session_destroy();
session_unset();
header('Location: index.php');
}
}
?>
Simple Logout Button
<a href="logout.php">Logout</a>
logout.php
<?php
if(isset($_GET['logout'])) {
session_start();
session_destroy();
header('Location: login.php');
exit;
}
?>
Or If Cookie Set Then
<?php
if(isset($_GET['logout'])) {
unset($_COOKIE['access_token']);
header('Location: login.php');
exit;
}
?>