2

How can I set a certain time to destroy a session? Can anyone show me the right way to destroy session after 10 minutes? Here is my code:

Session authorization:

session_start();
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
    header("location: index.php");
    exit();
}

Session logout:

session_start();
unset($_SESSION['SESS_MEMBER_ID']);
unset($_SESSION['SESS_FIRST_NAME']);
unset($_SESSION['SESS_LAST_NAME']);
header("location: index.php");

Session login:

if($result) {
    if(mysql_num_rows($result) == 1) {
        //Login Successful
        session_regenerate_id();
        $member = mysql_fetch_assoc($result);
        $_SESSION['SESS_MEMBER_ID'] = $member['id'];
        $_SESSION['SESS_USER_ID'] = $member['username'];
        $_SESSION['SESS_FIRST_NAME'] = $member['first_name'];
        $_SESSION['SESS_LAST_NAME'] = $member['last_name'];
        $_SESSION['SESS_USER_TYPE'] = $member['acc_type'];
        session_write_close();
        header("location: user_profile.php");
        exit();
    } else {
        header("location: loginerr.php");
        exit();
    }
} else {
    die("Query failed");
}
3
  • On front end setTimeout to call ajax function after 10 min, backend script called by ajax invokes session_destroy() Commented Aug 30, 2016 at 15:28
  • 10 minutes of inactivity or just 10 minutes? You can't log them out automatically but you can log then out when they attempt access after 10 minutes. Commented Aug 30, 2016 at 15:32
  • 10 minutes inactivity. Commented Aug 30, 2016 at 15:33

1 Answer 1

2

You can't, unless you roll your own session handling system. The default session cleanup system is run randomly. Every invocation of a PHP script that calls session_start() has a chance of triggering the garbage collector.

When the GC fires up, it basically rolls through the session storage directory and looks for any files which haven't been accessed in more than the default expiry period, and deletes any that are "stale".

By definition, if a session is used (e.g. session_start() is called and that particular session file gets loaded), then it cannot be stale and will not be deleted.

You'd need an external system to schedule the deletion, e.g. using the at scheduler.

Sign up to request clarification or add additional context in comments.

3 Comments

I would wait for clarification. You can log them out on access attempt after 10 min, or 10 min of inactivity. Just not automatically at the 10 min mark.
I would like to destroy session if anyone inactive for 10 min.
then set your session timeout for 10 minutes, and whenever the GC starts up, it'll auto-nuke any session files older than 10 minutes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.