Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Sessions expiry time - keeping session alive for a specific number of minutes/hours/days

I have a site that creates a Session for shopping carts.

$_SESSION['cart']=array();

It seems as if the server automatically kills the session after X time of inactivity, I assume this is set in php.ini (but my host does not grant me access, they just let me tell them the changes, so I cannot play around! :().

Is there a better way to keep the sessions alive for example for 2 days or for a specific number of minutes/hours?

like image 376
samyb8 Avatar asked Apr 19 '13 15:04

samyb8


People also ask

How do I keep a PHP session alive?

Using ajax you can call a php script that refreshes your session every 10 minutes. :) This is as far as i can go to "exact". <? php session_start(); // store session data if (isset($_SESSION['id'])) $_SESSION['id'] = $_SESSION['id']; // or if you have any algo. ?>

How can I limit session time 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.

Is it possible to set a time expire page in PHP?

By default, a session in PHP gets destroyed when the browser is closed. Session timeout can be customized, to make the user's page inactive after a fixed time. Starting session: The PHP, session_start() function is used to start a session in the web page.


1 Answers

Call session_set_cookie_params() before you call session_start() in your scripts:

$session_lifetime = 3600 * 24 * 2; // 2 days
session_set_cookie_params ($session_lifetime);
session_start();
// ...

From the documentation:

session_set_cookie_params()
Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script. Thus, you need to call session_set_cookie_params() for every request and before session_start() is called.

Alternatively, you could update your php.ini file's session.cookie_lifetime directive to 2 days (in seconds).

like image 133
Tim Cooper Avatar answered Nov 03 '22 17:11

Tim Cooper