Last time, I talked about what it would be like if WordPress supported sessions. Well, I decided to put my money where my mouth is and actually took the time to build it.
I’m proud to announce the very first release of an implementation of
This new object implements PHP’s
ArrayAccess behind the scenes, so it functions almost exactly like the standard
$_SESSION object. Just make a global reference to the object, then treat it like an associative array:
// A string
$wp_session['user_name'] = 'User Name';
// An array
$wp_session['user_contact'] = array( 'email' => 'firstname.lastname@example.org' );
// An object
$wp_session['user_obj'] = new WP_User( 1 );
On the back end, the object stores its data in WordPress transients – one transient per user – each with a unique ID provided by WordPress’
PasswordHash object to ensure uniqueness. If you’ve got a caching plugin installed that uses memcached, then transients (like options) can be cached in memory, making the system very performant.
On the front end, your session token is stored in a cookie, called
_wp_session. WordPress will read this cookie, find your session, and populate the global object for you automatically. At the end of its operation, WordPress will automatically write any changes to the session object back to the transient.
Since we’re aiming for as close to a 1:1 replacement for PHP’s standard session object as possible, version 1.0 of the class comes withe several WordPress-flavored helper functions:
wp_session_cache_expire()– get the session expiration time
wp_session_commit()– write session data out to the transient
wp_session_decode()– load data into the session from a serialized string
wp_session_encode()– write session data out to a serialized string
wp_session_regenerate_id()– change the ID of the current session to a new, random one
wp_session_start()– start the session and load data based on the user’s cookie
wp_session_status()– check the status of the current session
wp_session_unset()– clear out all variables in the current session
wp_session_write_close()– write session data and end session.
To make life easier,
wp_session_start() is wired to the
plugins_loaded action hook to make sure your session data is available as early as possible. Also,
wp_session_write_close() is wired to
shutdown to persist any changes to session data after all other functions have finished running.
Is is perfect? Probably not, but I’m comfortable enough with the class’ functionality to say it’s ready for a 1.0 release. You can download the tagged ZIP from GitHub, or you can fork the project to work on it yourself. If you have any recommendations, please submit a pull request so I can get them rolled in.
Remember, my ultimate goal is to get this class to be a part of WordPress core (hopefully in version 3.6). So the more refinement we can get, the better!