27

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.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Hensembryan
  • 1,067
  • 3
  • 14
  • 31

7 Answers7

42

The sessions on PHP works with a Cookie type session, while on server-side the session information is constantly deleted.

For set the time life in php, you can use the function session_set_cookie_params, before the session_start:

session_set_cookie_params(3600,"/");
session_start();

For ex, 3600 seconds is one hour, for 2 hours 3600*2 = 7200.

But it is session cookie, the browser can expire it by itself, if you want to save large time sessions (like remember login), you need to save the data in the server and a standard cookie in the client side.

You can have a Table "Sessions":

  • session_id int
  • session_hash varchar(20)
  • session_data text

And validating a Cookie, you save the "session id" and the "hash" (for security) on client side, and you can save the session's data on the server side, ex:

On login:

setcookie('sessid', $sessionid, 604800);      // One week or seven days
setcookie('sesshash', $sessionhash, 604800);  // One week or seven days
// And save the session data:
saveSessionData($sessionid, $sessionhash, serialize($_SESSION)); // saveSessionData is your function

If the user return:

if (isset($_COOKIE['sessid'])) {
    if (valide_session($_COOKIE['sessid'], $_COOKIE['sesshash'])) {
        $_SESSION = unserialize(get_session_data($_COOKIE['sessid']));
    } else {
        // Dont validate the hash, possible session falsification
    }
}

Obviously, save all session/cookies calls, before sending data.

Zombo
  • 1
  • 62
  • 391
  • 407
Exos
  • 3,958
  • 2
  • 22
  • 30
  • 5
    This seems like an overly complicated solution to a simple problem. What's wrong with setting the value of session.cookie_lifetime in your configuration or .htaccess file? The way you're suggesting requires additional code in each PHP file that requires session. – Francois Deschenes Jun 15 '11 at 17:45
  • Yes, but i write the simple solution (before "But, it..."), the rest or response is for "I Want to set it to forever", hehe, the session.cookie_fifetime, is server-side configuration, but the browser manage this as "session cookie". For the simple solution can be use session_set_cookie_params too. – Exos Jun 15 '11 at 19:29
  • Obviously the session i used is to save large data that change every 10 second as long as ajax request is exist. That's way i need to set it to forever. By the way, nice answer thanks – Hensembryan Jun 16 '11 at 06:09
  • 2
    Expire time in your example "604800", should be: "time()+604800", is an absolute reference. – Ignacio A. Poletti Nov 14 '13 at 00:45
  • You can set it in your php.ini to 0...thats forever. – M H Jun 26 '15 at 00:09
  • 2
    @Hanoncs Wrong, `session.cookie_lifetime` defaults to 0 in php.ini, and that means it's a session cookie, not that it lasts forever. – The Onin Dec 10 '15 at 12:47
  • what is valide_session function in your code? What does it do? – Robert Sinclair Jul 25 '16 at 12:02
27

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

Community
  • 1
  • 1
scasei
  • 457
  • 4
  • 4
17

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

reformed
  • 4,505
  • 11
  • 62
  • 88
Jose
  • 316
  • 2
  • 5
5

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.

Francois Deschenes
  • 24,816
  • 4
  • 64
  • 61
1

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
matrixb51
  • 67
  • 9
0

I dont see this mentioned anywhere, but setting ini_set('session.gc_maxlifetime', $max_lifetime); in the PHP file itself is usually not going to have the desired affect if the php.ini file has a LOWER value and the server hosts multiple domains/vhosts. If you have User on X website, and the maxlifetime is set to 10 seconds (not a real value, this is just for example) in the PHP file and then have the maxlifetime set to 5 in php.ini something interesting/unexpected will happen if you have multiple domains/vhosts.

When a 2nd user visits a site that HASNT set ini_set('session.gc_maxlifetime', $max_lifetime); in it's PHP file and it defaults to whatever php.ini has, that will cause PHP's garbage collection to fire using 5 seconds rather than 10 seconds as maxlifetime, thus deleting the user's session which was supposed to last at least 10 seconds.

Therefore, this setting should almost NEVER go in the PHP file itself and should actually be in the vhost entry if your setup has this capability and falls into this type of scenario. The only exception to this is if your server only hosts 1 website/vhost who's PHP files will always override whatever php.ini has.

This happens because all sites use the same tmp dir to store session data. Another mitigation solution would be to set the session tmp dir per vhost. And yet another (not recommended) solution is to simply disable session.cookie_lifetime completely in php.ini by setting it to 0.

helvete
  • 2,455
  • 13
  • 33
  • 37
totalnoob
  • 31
  • 6
  • `The value 0 means "until the browser is closed." Defaults to 0. See also session_get_cookie_params() and session_set_cookie_params().` https://www.php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime – Lepy Dec 22 '22 at 12:33
-4

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

Naftali
  • 144,921
  • 39
  • 244
  • 303