5
  1. How to set the php session time out, I'm trying like below, but I dont think it works

    ini_set("session.gc_maxlifetime", 600);

  2. How to find out whether a php session exists or expired using ajax (javascript)?

Regards

4
  • 2
    Dunno about the first but the second is not really possible: if you send AJAX requests on regular intervals you keep the session alive for good. Commented Apr 8, 2011 at 19:02
  • @Shadow - while technically true if the session is cleared then a new session is recreated. He can use AJAX to check for a specific value Commented Apr 8, 2011 at 19:10
  • @Cfreak true, but if the AJAX is sent every minute for example, it will keep the session alive forever as far as I can tell. Commented Apr 8, 2011 at 19:12
  • The session wouldn't get cleaned up if the AJAX script pings at an interval shorter than the expiring limit. however, the session will not just vanish after the timeout period. It's a probabilistic function, and can live anywhere from 0 hits to infinite hits AFTER the expiry time. Commented Apr 8, 2011 at 19:36

2 Answers 2

9

For #1 use session_set_cookie_params(). To expire after 600 seconds

session_set_cookie_params(600)

(note unlike the regular setcookie function the session_set_cookie_params uses seconds you want it to live, it should not be time() + 600 which is a common mistake)

For number 2 just make a small script called through AJAX:

<?php
session_start()

if( empty($_SESSION['active']) ) {
     print "Expired"
}
else {
     print "Active"
}

?>

On the Javascript side (using JQuery)

$.get('path/to/session_check.php', function(data) {
     if( data == "Expired" ) {
         alert("Session expired");
     } else if (data == "Active" ) {
         alert("Session active");
     }
 });
Sign up to request clarification or add additional context in comments.

Comments

2

What Shadow Wizard commented about keeping the session alive every time you do the check is true.

But the solution is quite simple. The trick is to perform the AJAX request at an interval larger than the session life time. So if you establish a session timeout of 15 minutes you can check via AJAX every 16 or more.

In order for the above to work, the session timeout is something that you should implement manually. You can read this usefull answer on how to set the session duration.

Hope this helps you or anyone who is looking for the same!

Comments

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.