Using WordPress for Web Application Development: Features: Sessions

In this series, we’re taking a look at how it’s possible to build web applications using WordPress.

Thus far, we’ve talked about how WordPress is a foundation (rather than a framework), its architecture, how we need to conceptually think of it when approaching it especially coming from other languages, and then we began talking about the components that make up a basic web application.

As a reminder, we mentioned:

  • User management
  • Permissions
  • Session management
  • Email functionality
  • Data serialization and retrieval
  • URL Routing (sometimes referred to as URL rewriting or rewrite rules or even just routes)
  • Caching
  • Support for custom queries

And starting in the last post, we covered both User Management and Permissions.

In this post, we’re going to be taking a look at how to incorporate sessions within a WordPress-based application; however, we’re going to assume that you – or other readers – aren’t familiar with sessions at all.

So we’ll start at a high-level view of sessions, talk about the relationship between sessions and WordPress, and then how to begin incorporating sessions into your WordPress-based application.

An Introduction to Sessions

For those of you who aren’t familiar with the concept of sessions, it’s relatively simply to understand (but can be difficult to implement depending on the framework or foundation that you’re using).

In short, sessions are a way to maintain the state of an application across page loads.

But here’s the thing: This can be implemented in a number of ways. In one scenario, you could simply write data to the database on one page, then retrieve it on the next.

This isn’t exactly the most efficient way to set a session especially if you have a lot of active users, but it does allow you to maintain state.

Then again, that’s not what we’re talking about when we’re referring to sessions. Instead, we’re talking about keeping a set of information persistent in memory – literally, in RAM – throughout the time that the user is active on the website.

At the risk of getting more technical than I’d like in this series of articles, there are ways in which sessions are managed a bit different so that you can leave a site, come back, and still have your active session maintained.

Think about services such as Twitter when you don’t have to login each time you visit the site. Regardless, the details of that implementation are beyond the scope of this series.

Instead, let’s consider for a moment what a session would look like from the time a user landed on the homepage of an application, logged in, established a session, and then logged out.

Loading an Application Without a Session

So here’s what a typical database-backed application looks like from the perspective of not maintaining any session information. Instead, everything is statically provided on pages and/or it’s loaded from the database:

A simple example of a database-backed web application.
A simple example of a database-backed web application.

Pretty easy to understand, isn’t it?

Basically, each time a page loads – or each time a user navigates to a new page – the page will retrieve the necessary information from the database and then present it to the user.

Loading an Application With a Session

If the above diagram shows what a database-backed web application looks like without any type of session mechanism, what does it look like when it does offer support for sessions?

Before we look at a diagram of what it’s like, let’s set out the following parameters:

  • The application will maintain no session for users who are not logged in
  • The application will store certain information in the session once the user has logged in
  • The session will be destroyed when the user logs out

In short, this means that once the user is logged in, some information will be displayed from static information, information in the database, and information stored in the session.

A simple example of a session-enabled web application.
A simple example of a session-enabled web application.

Nothing terribly complicated, huh?

In short, information is loaded into a session that’s stored in memory and retrieved from there when it’s needed. Other information that’s not in session but is relevant to the page being displayed will be retrieved from the data.

Permitting this is implemented correctly, you can really squeeze a lot of performance out of an application and make the overall user experience a bit better; however, the details of that are beyond this particular article.

The most important take away from this particular section is how sessions work, and what benefits they offer.

The Truth About WordPress and Sessions

For anyone that has worked with building web applications in other frameworks, you’re likely familiar with sessions and how they work within the context of the given tools that you were using.

In fact, if you’ve done any prior work with PHP, you’re likely familiar with how sessions work, as well.

But here’s an interesting fact (at least, I think it’s interesting!):

The core WordPress application does not use sessions.

In fact, the only time it comes close to maintaining any type of state is through the use of a cookie that’s generated when you login to the application.

How Do We Implement Sessions?

When it comes to implementing sessions in WordPress, it’s more a matter of understanding how to implement a session in PHP and making sure that you do the proper housecleaning, when necessary.

Specifically, this means that you know how to:

  • Start the session
  • Store information in a session
  • Retrieve the information from the session (and how to retrieve information from the database if it’s not in a session)
  • Destroy the session

Sounds simple enough, doesn’t it? For the most part, it is but, as with most things in development, there are things that we must consider.

Start the Session

The first thing that you need to note is that sessions must be started. This is done by calling PHP’s session_start() function.

There are two things to note about starting a session in PHP:

  1. You only want to start a session if a session ID doesn’t exist
  2. You must start a session before any information is output to the browser

To do this, you can define a function using an appropriate hook but it must be early enough in the WordPress page lifecycle.

For the purposes of the example of this article, I’m going to be starting a session if a user is logged in. If a user is logged in, then we’ll store the time at which they logged in; otherwise, we won’t do anything.

Case in point: In the code below, I’m starting a session during WordPress’ init action.

 function example_login() {  	if ( ! session_id() && is_user_logged_in() ) { 		session_start(); 	} } add_action( 'init', 'example_login' ); 

Now with a session started, we can actually begin storing information.

Store Session Information

Working with session data is very similar to working with data stored in $ _GET, $ _POST, or even in a normal associative array. In short, PHP offers the $ _SESSION collection that allows us to store information via key/value pairs.

In continuing with the example above, we’ll store the current time at which the user logged in. Note, however, that we must first check if the value is set in the collection; otherwise, we will overwrite it every single time.

 function example_login() {  	if ( ! session_id() && is_user_logged_in() ) {  		session_start();  		if ( ! isset( $  _SESSION['time'] ) ) { 			$  _SESSION['time'] = time(); 		}  	} } add_action( 'init', 'example_login' ); 

Simple enough – first, I check to see if a session_id() is set and I check to see if the user is logged in. If so, store the time.

But now we need to actually retrieve the information from the session elsewhere in the codebase.

Retrieve Session Information

Just as it is when storing information in arrays, we can retrieve the information much in the same way, but there’s one caveat: we have to make sure the value is set in the array and that it’s not empty.

We can do this using a simple conditional:

 if ( isset( $  _SESSION['time'] ) && ! empty( $  _SESSION['time'] ) ) { 	print_r( $  _SESSION['time'] ); } 

Assuming that the value is present in the $ _SESSION collection, then we should be good to go.

Destroy the Session

This can be done on logout. Using the code provided, you should see a difference in your site based on if you’re logged in or not.

Finally, since we’re establishing a session when the user is logged in, we want to destroy the session whenever the user logs out. This is relatively simple using PHP’s session_destroy() function; however, there are some finer nuances that must be understood.

Straight from the PHP manual:

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie

In short, this means that the mechanism for persisting session information is destroyed, but the values that are kept in the session collection are still maintained.

 function example_logout() {  	if ( session_id() ) { 		session_destroy(); 	}  } add_action( 'wp_logout', 'example_logout' ); 

But, again, as with other associative arrays and collections in PHP, you can reset those values (or overwrite them). Regardless, that’s going beyond the scope of this particular series.

There Are Some Gotchas!

What would an article about programming be without some type of gotchas, right?

First, we’ve already established that WordPress core itself is stateless. Not only that, but it also maintains a function that is used to reset globals (you can find this function in wp-includes/load.php – just look for wp_unregister_GLOBALS).

When looking at the source code, you’ll notice the following lines:

 $  input = array_merge( $  _GET, $  _POST, $  _COOKIE, $  _SERVER, $  _ENV, $  _FILES, isset( $  _SESSION ) && is_array( $  _SESSION ) ? $  _SESSION : array() ); foreach ( $  input as $  k => $  v ) 	if ( !in_array( $  k, $  no_unset ) && isset( $  GLOBALS[$  k] ) ) { 		unset( $  GLOBALS[$  k] ); 	} 

This goes to unset values in the session, so, in a sense, WordPress may actually try to unset your session.

Secondly, not all web hosts support PHP sessions or the $ _SESSION collection. To that end, you need to make sure that the environment into which you’re deploying your work offers the necessary configuration and support for what you’re releasing.

What’s a Developer to Do?

So if you’re worried about having to manage a lot of code to ensure that sessions work within WordPress (and aren’t trashed) while doing so, and you also don’t want to deal with the various hosting environments and their various configurations, then I highly recommend checking out Eric Mann’s work on WP_Session.

This particular project is outside the scope of what we’re trying to cover here in this article; however, this plugin is worth checking out as it provides a great session management layer for WordPress without a lot of the overhead that we’ve covered here.

Do Sessions Even Matter?

First, recall that sessions are not unique to WordPress. They are a feature of PHP that we’re able to implement within the context of WordPress. And to that end, we’re able to introduce some really cool functionality based on the needs of the users.

But this raises the question: do sessions matter?

I find this question is a bit subjective.

If you’re building a web application in which each user needs to be walking around the site with information unique to their session – such as, say, their first name, last name, last time of login, and other fun stuff – then, yeah, I think you have a case for using a session.

But if you’re building something that requires nothing more than authentication before rendering information from a database, then I’d question whether or not you need to implement a session.

All of that to say: It depends on the nature of your project.

At this point, we’re ready to move on to the next common component of web applications: email.

Rather than relying on PHP and wiring it into the WordPress lifecycle, the WordPress API makes working with email relatively trivial, and really powerful. And with that, we’ll review it in the next article.

Leave a comment

Your email address will not be published.