[php] How to set lifetime of session

How to set session lifetime in PHP? I Want to set it to forever as long as the request is exist. The request is AJAX. My PHP code that handle AJAX request is:

// AJAX.php
<?php    
session_start();

$_SESSION['counter'] = $_SESSION['counter'] + 1;

header('Content-type: application/json');    
echo json_encode(array('tick' => $_SESSION['counter']));
?>

and the JavaScript:

$(document).ready(function() {            
function check() {
    getJSON('ajax.php');        
}

function getJSON(url) {                                
    return $.getJSON(
                url,
                function(data) {
                    $("#ticker").html(data.tick);
                }
           );
}

setInterval(function() {
    check();
}, 10000); // Tick every 10 seconds

});

The session always resets after 300 seconds.

This question is related to php session lifetime

The answer is


Since most sessions are stored in a COOKIE (as per the above comments and solutions) it is important to make sure the COOKIE is flagged as a SECURE one (front C#):

myHttpOnlyCookie.HttpOnly = true;

and/or vie php.ini (default TRUE since php 5.3):

session.cookie_httponly = True

Set following php parameters to same value in seconds:

session.cookie_lifetime
session.gc_maxlifetime

in php.ini, .htaccess or for example with

ini_set('session.cookie_lifetime', 86400);
ini_set('session.gc_maxlifetime', 86400);

for a day.

Links:

http://www.php.net/manual/en/session.configuration.php

http://www.php.net/manual/en/function.ini-set.php


As long as the User does not delete their cookies or close their browser, the session should stay in existence.


Prior to PHP 7, the session_start() function did not directly accept any configuration options. Now you can do it this way

<?php
// This sends a persistent cookie that lasts a day.
session_start([
    'cookie_lifetime' => 86400,
]);
?>

Reference: https://php.net/manual/en/function.session-start.php#example-5976


Sessions can be configured in your php.ini file or in your .htaccess file. Have a look at the PHP session documentation.

What you basically want to do is look for the line session.cookie_lifetime in php.ini and make it's value is 0 so that the session cookie is valid until the browser is closed. If you can't edit that file, you could add php_value session.cookie_lifetime 0 to your .htaccess file.