How do I create persistent sessions in PHP?

John Hoffman picture John Hoffman · Mar 21, 2012 · Viewed 33.1k times · Source

I used session_start() to initiate a session in PHP, but when my browser closes, the session is gone.

How do I use PHP to create persistent sessions that last across browser closes?

Answer

drew010 picture drew010 · Mar 21, 2012

See the php.ini value session.cookie_lifetime.

The default value of 0 means to end the session when the browser closes.

You can override this value either directly in php.ini or set it in your application prior to starting the session using ini_set. Setting it to something greater than 0 will cause the session to live for that duration.

E.g.

ini_set('session.cookie_lifetime', 60 * 60 * 24 * 7);  // 7 day cookie lifetime
session_start();

The above example causes the session cookie to be set with an expiration of 7 days from when the session is started.

Note: If you start your session for all of your webpages from the same piece of code, this will not continue to extend the session expiration each time session_start() gets called. The cookie lifetime is set from when the session is first started, not on subsequent requests. If you want to extend the lifetime of a session out 7 days from the current time, see also session_regenerate_id().

Also Note: If your session.gc_maxlifetime value is set to something less than the length of the session cookie, you can have a situation where the user does not visit the site for 5 days and when they return, the session cookie is no longer valid because the data on the server has been deleted. To remedy this, you should also set the lifetime for this session data to be at least as long as your cookie lifetime. As the manual states, it may be necessary to use a custom session.save_path for the session data you want to persist longer than the default. Therefore, your script may look like this:

ini_set('session.cookie_lifetime', 60 * 60 * 24 * 7);
ini_set('session.gc_maxlifetime', 60 * 60 * 24 * 7);
ini_set('session.save_path', '/home/yoursite/sessions');
session_start();