2020-09-30

How to logout after X minutes of inactivity on button click?

I am working on a simple project where I have a login system with multiple users where each user will login and save form entries in a file. I am trying to build session timeout so that after 2 minutes of inactivity it can log me out.

  • I have login.php page where I provide my user and password.
  • If login is successful then it redirects me to index.php page where I have form with two textbox and a button.
  • On index.php page I have Save Data button which if I click it calls save.php then it save form entries by overwriting in file.
  • I also have logout link on my index.php page which if I click then it will log me out and redirect to login.php page.

All above things works fine. Now I am trying to build this session timeout so that it can log me out after x minutes of inactivity and redirect me to login.php page.

Here is my index.php file:

<?php

declare(strict_types = 1);

// Start session.
session_start();

// Include helper functions.
require_once 'helpers.php';

// 2 mins in seconds
$inactive = 120; 

if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['timeout'];
    if($session_life > $inactive)
    { 
        redirect('logout.php');
        return;
    }
}

$_SESSION['timeout'] = time();

// Redirect user to login page if not authenticated.
if (! check_auth()) {
    redirect('login.php');
    return;
}

?>
<!doctype html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <div>
        <h1>Website Title</h1> <a href="logout.php">Logout</a> </div>
    <div>
        <p>Welcome back, <?= $_SESSION['user_id'] ?>!</p>
    </div>
    <form method="post">
        <input type="text" name="field1" />
        <input type="text" name="field2" />
        <input type="submit" name="submit" value="Save Data"> </form>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
    $(function() {
        $('form').submit(function(e) {
            e.preventDefault();
            $.post({
                url: 'save.php',
                data: $(this).serialize(),
            }).done(response => {
                response = JSON.parse(response);
                if(response.message) {
                    alert(response.message);
                }
            });
        });
    });
    </script>
</body>
</html>

Here is my save.php file:

<?php
declare(strict_types=1);
// Start session.
session_start();
// Include helper functions.
require_once 'helpers.php';

// 2 mins in seconds
$inactive = 120; 

if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['timeout'];
    if($session_life > $inactive)
    { 
        redirect('logout.php');
        return;
    }
}

$_SESSION['timeout'] = time();

// Redirect user to login page if not authenticated.
if (! check_auth()) {
    redirect('login.php');
    return;
}

// save form entries in a file

Here is my helpers.php file:

<?php
declare(strict_types=1);

if (! function_exists('check_auth')) {
    function check_auth(): bool
    {
        return isset($_SESSION['user_id']);
    }
}

if (! function_exists('logout'))
{
    function logout()
    {
        if (isset($_SESSION['user_id'])) {
            $trace = json_decode(file_get_contents('current_user.txt'));

            if ((int) $trace->user_id === $_SESSION['user_id']) {
                $content = isset($trace->revoked_user_id)
                ? json_encode(['user_id' => $trace->revoked_user_id, 'created_at' => (new DateTime('now'))->format('Y-m-d H:i:s')])
                : '';
                file_put_contents('current_user.txt', $content);
            }

            unset($_SESSION['user_id']);
            unset($_SESSION['timeout']);
        }
    }
}

if (! function_exists('redirect')) {
    function redirect(string $url, int $status_code = 303): void
    {
        header('Location: ' . $url, true, $status_code);
        die();
    }
}

Here is my logout.php file:

<?php
declare(strict_types=1);

// Start session.
session_start();

// Include helper functions.
require_once 'helpers.php';

logout();

redirect('login.php');

Problem Statement

I am redirecting to logout.php file once it is idle for 2 minutes in index.php and save.php. Here is what I am noticing -

  • If I am on index.php page and after 2 minutes of inactivity, if I refresh my browser then it logs me out fine without any issues and redirects me to login.php page.
  • Now let's say If I am on index.php page again and after 2 minutes of inactivity if I click on Save Data button then it gives me error on my console but techincally it should have logged me out and redirected me to login.php page.

Below is the ajax call I have in my index.php page -

<script>
$(function() {
    $('form').submit(function(e) {
        e.preventDefault();
        $.post({
            url: 'save.php',
            data: $(this).serialize(),
        }).done(response => {
            response = JSON.parse(response);
            if(response.message) {
                alert(response.message);
            }
        });
    });
});
</script>

I get a json parsing error for my point 2 whenever I click Save Data button after 2 minutes of inactivity. And value of response variable is full login.php in html. I am not sure why it is happening. Do we need to check for session validation in jquery itself before it calls save.php?



from Recent Questions - Stack Overflow https://ift.tt/3kVkVCj
https://ift.tt/eA8V8J

No comments:

Post a Comment