DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Data
  4. Practical PHP Patterns: Client Session State

Practical PHP Patterns: Client Session State

Giorgio Sironi user avatar by
Giorgio Sironi
·
Aug. 30, 10 · Interview
Like (0)
Save
Tweet
Share
1.87K Views

Join the DZone community and get the full member experience.

Join For Free

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']);
PHP Session (web analytics) Data (computing)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • DevOps vs Agile: Which Approach Will Win the Battle for Efficiency?
  • Tracking Software Architecture Decisions
  • Fargate vs. Lambda: The Battle of the Future
  • Use Golang for Data Processing With Amazon Kinesis and AWS Lambda

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: