Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

PHP Session Time out- Auto Logout

I am trying to get my PHP portal to auto logout after 5 minutes of inactivity. Here is the login Script.. What would i need to add to make this happen?

<?php
session_start();
ob_start();
//Include the database connection file
include "database_connection.php"; 
//Check to be sure that a valid session has been created
if(isset($_SESSION["VALID_USER_ID"]))
{

    //Check the database table for the logged in user information
    $check_user_details = mysql_query("select * from `signup_and_login_users_table` where `username` = '".mysql_real_escape_string($_SESSION["VALID_USER_ID"])."'");
    //Validate created session
    if(mysql_num_rows($check_user_details) < 1)
    {
        session_unset();
        session_destroy();
        header("location: login.php");
    }
    else
    {

    //Get all the logged in user information from the database users table
    $get_user_details = mysql_fetch_array($check_user_details);

    $user_id = strip_tags($get_user_details['id']);
    $fullname = strip_tags($get_user_details['fullname']);
    $username = strip_tags($get_user_details['username']);
    $email = strip_tags($get_user_details['email']);
    $passwd = strip_tags($get_user_details['password']);
    $user_access_level = strip_tags($get_user_details['user_level']
    );
?>

1 Answer

Hello,

I haven't really dug into doing an auto log out feature on the sites that I've developed, however; what I would probably do is use jQuery to store the exact time when a user has logged in or performed an action on the site. Then I would use jQuery's setInterval() function to run a custom jQuery function checking if the user has been logged in or inactive for more than an allotted time (say 5 minutes). I would set the delay to every 60 seconds or even every second to run this function. If the validation in that function is true, I would then transfer that user to your log out page where it would log the user out.

Again I haven't done anything like this before, but this is how I would go about doing it if I had to. Hope this helps.

Cheers!

could you see if you could do it?