Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Practical PHP Patterns: Client Session State

DZone 's Guide to

Practical PHP Patterns: Client Session State

· Web Dev Zone ·
Free Resource

Even the most thin-client architectures need some storage on the client, at least for a session identifier. The HTTP protocol has a stateless nature, and if we exclude its troublesome authentication mechanism, requests can't be natively grouped by client.

The Client Session State pattern is the choice of storing all session data on the client, so that it is sent back with every request and updated in some responses. The mechanisms for accomplishing this vary.

While using this pattern, the server can remain completely stateless (for what regards the session data at least; it probably has some general state like a database). Clustering is not a problem as you can switch the user between servers easily and routing requests independently.

Advantages

Before talking about the means available to store data on the client, let's expose the advantages of this pattern.
As we have seen earlier, we hit a maximum in servers resiliency: they can be stateless, with no problem of clustering (multiple machines that serve the same logical function), and no data loss in case of a failover.

Besides that, the more the data is small, the more the pattern works well. With more data it breaks down both due to larger requests and responses size, and for the complexity of dealing with all the data (the second problem is solved with solutions like serializing everything).
Moreover, this pattern is necessary at least to store session ids, even if a pattern like Server State is used.

Disadvantages

There are many issues which make this pattern not always viable.

A first problem resides in transmitting the state over the wire, in a protocol without types like HTTP where everything is a string, and sometimes between different languages like PHP and JavaScript. Every data structure should be serialized with PHP native functionalities or in a format such as JSON or XML, to allow easy parsing when it is sent back.

Obviously, if the state of the interaction grows in size every request will carry it as an heavy payload, since the server remains stateless.
Another great problem is that all of the means that use the client as a storage are fundamentally vulnerable to the user's tampering: you cannot store on the client things like an admin role, nor permissions.

Implementation

There are essentially three means to store data on the client in web applications.

URL parameters

With plain old parameters, GET parameters are valorized to maintain the state of the interaction, and each link has them. Usually platforms with automatic URL rewriting are used to render it feasible. This solution also limits the size of the URL, and prevent the use of boomarks and the sharing of links, since every user has its different URLs.

This implementation has been abandoned for every kind of sensitive data, but it's so simple and functional that emerges everywhere without noticing. For example, Youtube produces links like youtube.com/watch?v=...&feature=related, which tells the server to display related videos on the side of the one being vatched.

Hidden fields

This solution prescribes to send parameters via POST instead of GET, and store them in hidden fields. The navigation is then obtained via form buttons or JavaScript widgets that submit them.

With URL parameters the user sharing the URL shares also his session parameters; with hidden fields copying the URL in a different tab means losing session data. Very uncommon and found in legacy systems or applications produced by an higher-level abstraction which remembers automatically to put hidden fields in every page.

Cookies

Cookies are sent back and forth as part of the HTTP headers, and can maintain every kind of string data.

They are always included in requests made from the client to the server, while are sent in the response from the server to the client only on creation or  updating, a fact which saves some bandwidth.

Cookies were originally controversial and not accepted by all users, but are now the standard: no one remembers how to turn off cookies anymore as every website requires them. Even private browsing sessions - the famous porn mode - store cookies temproarily to delete them at the browser's closing.

Example

The code sample discusses how to transmit a PHP object back and forth with cookies. Thanks to PHP native support, it's very simple.

Beware that large object graphs cannot be transmitted this way, nor graphs that contain transient resources like database connections. However, a Data Transfer Object or a Memento can be stored flawlessly.

<?php
/**
* An object without external references, ideal to transmit over the wire
* Which objects are adapt should be discussed case by case.
*/
class UserPreferencesDTO
{
/**
* All private|protected|public fields will be serialized,
* since no __sleep() method is defined
*/
private $_resultsPerPage;
private $_displayBigImages;
private $_ajax;

/**
* The object is immutable, as we can simply create a new one when preferences change.
*/
public function __construct($resultsPerPage = 20, $displayBigImages = true, $ajax = true)
{
$this->_resultsPerPage = $resultsPerPage;
$this->_displayBigImages = $displayBigImages;
$this->_ajax = $ajax;
}

public function getResultsPerPage()
{
return $this->_resultsPerPage;
}

public function getDisplayBigImages()
{
return $this->_displayBigImages;
}

public function getAjax()
{
return $this->_ajax;
}
}

// on requests where the preferences change
$userPref = new UserPreferencesDTO(10, false, false);
setcookie('userPreferences', serialize($userPref), time() + 3600 * 24 * 365);

// later, every time the data is needed
$userPref = unserialize($_COOKIE['userPreferences']);
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}