Remember me with PHP – hack it #6

PHP persistent sessions
“Remember me” functionality was recently implemented on the Supernifty login screens. The PHP documentation is surprisingly non-obvious so here’s how to do it.

If you’re already using the $_SESSION variable, the default is for this variable to live only for as long as the browser. Once the user closes the browser, the cookie will be deleted, and they’ll be logged out.

To remember a user across browser sessions, here’s what needs to be done.

Tell the browser to remember the session

You do this with the line:

setcookie( session_name(), session_id(), time() + 86400*30 );

This overwrites the default session cookie, with a cookie that will persist on the user’s browser for one month.

Note that since cookies are set in the headers sent to the browser, this needs to be done before writing any content to the browser.

With HTML like

<input type="checkbox" name="remember" value="remember"/>

You could have a handler like:

$remember = $_POST['remember'];
if ( isset( $remember ) && $remember == 'remember' ) {
setcookie( session_name(), session_id(), time() + 86400*30 );
}

Tell the server to remember the session

Bizarrely, PHP’s default session time is something ridiculous like 24 minutes.

To tell the server to remember the session for longer, you need to set some PHP environment variables, like so:

ini_set("session.gc_maxlifetime","2592000"); // 24*30 hours
session_set_cookie_params( 86400*30 );
session_start();

More details about PHP’s session lifetime

With these two pieces in place, you can now implement a “remember me” checkbox on your login screen with PHP, while continuing to use the $_SESSION variable.

Leave a Reply