2

I want to clear the session variables when the tab is closed but I could not find any solutions so far. here user without login they will enter the url dashboard.php means it will redirect to index.php, this condition is working fine, now user successfully login means it will go to dashboard.php page after that user close this tab and again they will enter dashboard.php page means i want to redirect the page in index.php, how can do this

<?php
  session_start();
  date_default_timezone_set('Asia/Kolkata');
  include('dbconfig.php');
  $email=$_POST['email'];
  $password=$_POST['password'];
  $password=md5($password);
  $sql=mysql_query("SELECT id,username,email,password,is_user_type FROM login WHERE email='$email' AND password='$password'");
  list($id,$username,$email,$pwd,$is_user_type)=mysql_fetch_row($sql);
  if($pwd==$password){
  $_SESSION['username']=$username;
  $_SESSION['email']=$email;
  $_SESSION['is_user_type']=$is_user_type;
  $_SESSION['current'] = basename($_SERVER['PHP_SELF']);
   header("Location:dashboard.php");
  }
  else{
      echo "error";
     }
    ?>

dashboard.php
<?php
session_start();
if(!isset($_SESSION['email']) && empty($_SESSION['email'])) {
  header("Location:index.php");
}
if (isset($_SESSION['current'])) {
 if (basename($_SERVER['PHP_SELF']) != $_SESSION['current']) {
    session_destroy();
 }
 }
?>

2 Answers2

1

First, your xyz.php file set a unique variable in the $_SESSION array which will act as a mark that the user has been on this page

$_SESSION['previous'] = basename($_SERVER['PHP_SELF']);

Then, add the following code on all pages, before any output to check if the user is coming from xyz.php

if (isset($_SESSION['previous'])) {
   if (basename($_SERVER['PHP_SELF']) != $_SESSION['previous']) {
    session_destroy();
    unset($_SESSION['previous']);
   }
}
Pravin Vavadiya
  • 3,195
  • 1
  • 17
  • 34
  • Thanks Mr @ Pravin Vavadiya – vaishnavee N Dec 03 '16 at 13:30
  • please check my updated code,successfully logged means it will go to dashboard.php page.then i refresh the page means again it will come to login page,should not come like this – vaishnavee N Dec 05 '16 at 07:43
  • "add the following code on all pages, before any output to check if the user is coming from xyz.php".. in your dashboard.php first add this code after check email seesion.... – Pravin Vavadiya Dec 07 '16 at 06:52
0

To remove particular session data , try this

  if($_SESSION[sessionvaribale] )
  {
   unset($_SESSION[sessionvaribale]);
   }

To destroy all session data - try session_destroy()

Its already discussed by Stackoverflow

Refer Session destroy when logout

Community
  • 1
  • 1
maha lakshmi
  • 57
  • 1
  • 2
  • 9