Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a PHP session exists or expired using AJAX

  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

like image 306
user237865 Avatar asked Apr 08 '11 18:04

user237865


People also ask

How to display session time in PHP?

Use the unset() Function to Set the Session Timeout in PHP This method stores the session in an array. We can use the associative array to store the session name and the session start time. We can use the time() function to get the current time.

How to set session time limit in PHP?

The timeout limit of the session can be set by setting the value of two directives in the php. ini file or using the ini_set() function in the PHP script. The directives are given below. It is used to set the time limit in seconds to store the session information in the server for a long time.


1 Answers

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");
     }
 });
like image 50
Cfreak Avatar answered Oct 23 '22 06:10

Cfreak