Sarah
Sarah

Reputation: 1905

Where to call session_unset(user)

I have a side bar with a category "abc". On clicking a pop up div loads asking the user to login or register. Once the user logs in it loads the page "xyz.php". In order to prevent direct access to "xyz.php" I am creating a session variable on post and checking in the "xyz.php" if the session variable exists:

<?php
session_start();
if (!isset($_SESSION['logged_in']))
    header("Location: index.php");
?>

This works perfectly fine and I am able to block direct access to the above link. However, once the user logs in, the page can be accessed directly. In order to prevent this, I am releasing the session variable through:

<?php 
session_start(); 
session_unset('logged_in'); 
?>

However, I am calling this in the index file and only if the user visits the home page the session variable will be unset. How can I unset the session variable across the website once the user has logged in and the page has loaded? The page should load again only after the user has entered the login credentials again. There is no logout mechanism in place and is not desired.

Upvotes: 1

Views: 190

Answers (2)

Liftoff
Liftoff

Reputation: 25412

As per the comments above, I figured I would elaborate a bit, and this is not fit for comments, so here you go.

It is common practice to terminate a session due to inactivity by setting a timeout in your session variables.

Let's say that you want to terminate the session after 30 minutes of inactivity, whether that is because the user has not done anything on your website for 30 minutes or they have navigated away from it entirely.

You can manage this by creating a variable in your session (for this example, we'll call it last action) and storing the timestamp of the last user action in it. Update this on every page refresh and change and check if the time since the last action is greater than the timeout threshold. If so, kill the session.

Create a file named "updateSession.php":

<?php

    session_start();
    if((time() - $_SESSION["lastAction"]) > 1800) //1800 == 30 minutes
    {
        session_destroy();
        header("Location:/timeout");
        return;
    }

    $_SESSION["lastAction"] = time();

?>

Then just include this file in every page:

include "{$_SERVER["DOCUMENT_ROOT"]}/path/to/updateSession.php";

Upvotes: 2

Ambarish Yadav
Ambarish Yadav

Reputation: 412

You may use this code you have to get user id then check the condition that

 <?php
    session_start();
    if (!isset($_SESSION['logged_in'] && $_SESSION['user_id'] !== User_id ))
        header("Location: index.php");
    ?>

Upvotes: 0

Related Questions