Saturday, March 29, 2014

Automatic logout after session expires in PHP

I have written this article for automatic logout after session expires.

Please use the following code

<?php
$timeout = 600; // Number of seconds until it times out.

// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
    // See if the number of seconds since the last
    // visit is larger than the timeout period.

    $duration = time() - (int)$_SESSION['timeout'];
    if($duration > $timeout) {
        // Destroy the session and restart it.        session_destroy();
        session_start();
    ?>
        <script>
            alert("Your session was expired.Please login again to continue");
            window.top.location='login.php';
        </script>
    <?php
    }
}

// Update the timout field with the current time.
$_SESSION['timeout'] = time();

?>

1 comment: