PHP Session Management Using Redis

READ WHOLE ARTICLE

PHP Redis Session Management

For one of our client projects a server farm is used, that employs Redis servers as cache and sessions handler. This particular DBMS has been selected because it is open source (distributed under the BSD license), cross-platform, has an over the peak performance and allows for the organization of the server clusters.
One of the key problems of web programming is the user data storage in the intervals between their connections to the server. Today for this purpose, so-called cookies (on the client side) and session management (on the server-side) are used.

In this article, we strive to describe the PHP session in Redis and when to use Redis.

What is session management?

HTTP is the protocol, each regular exchange of data in which is independent of previous queries. PHP session management creates such dependence. Most of the web applications need to keep track of certain states of a particular user. This may be the contents of the shopping basket or the id of the logged user. Without saving the PHP custom session handler, the user would have to authenticate with every request.
The web server does not support a permanent connection with the client, and each request is treated as new, without any connection with the previous ones. That is, it is possible neither tracking any requests from the same visitor nor saving variable values between viewing the individual pages. As a solution to these problems, the session management extension was invented.
The session, in a nutshell, is a mechanism to uniquely identify the browser and create the tracker file for this browser on the server in which the session variables are stored.

what is session management

The most popular web development language today is deservedly PHP, because of its ease of learning, convenience, and speed of development, significantly higher than those of the competition. Moreover Multi-Programming Solutions is one of full stack web development firm that provides the whole range of services you need. However, the classical method of the session management in PHP (native through PHP session handler library or using Memcached service session handling), one of which is the complexity of its use in the server clusters, for example. However, the same can be said of most alternatives of the PHP – Perl, JavaScript, Ruby. In this regard, the majority of experienced web developers have invented their own custom solutions to the problem of user session storage for repeated connections.

What is redis and what is it used for?

Why use Redis? Redis (REmote DIctionary Server) is an open source advanced structural key-value pairs server storage tool. It is often suggested as a DBMS because it allows for a wide range of values, including indexes, hashes, strings, lists, and orderly rows, to be used as keys. Also, the Redis session handler is useful for PHP session storage and retrieval.

Typical Redis usage scenarios can include:

  • User sessions and profiles storage.
  • Queue server with publish/subscribe mechanism.
  • Complete replacement of the Memcached in the role of the cache manager, moreover, in the case of the Redis, we get replication, longer keys, and values, the ability to recover cache from a disk, etc.
  • Operational variables, various flags and query parameters storage set up.
  • DBMS.
  • The role of “dictionary” in sharding, i.e. a server that “knows”, what shards are stored at which servers.
  • Storage of intermediate results of calculations in the processing of large data volumes.
Redis

Redis alternative, as mentioned earlier, is Memcached, which is extremely limited in its possibilities and performance compared to Redis.

Case description

In this section, we describe the PHP Redis example. The project uses several web servers, requests between which are distributed randomly (i.e., the same user may, at the first request, receive a response from one server, and the second – from the other).

By default, the session is stored in files on the disk of the server which has established the session. In order to obtain the same session data on different servers, a central session repository must be used.

Redis server was selected as such a repository. We have already used it as a caching, settings and log storage manager, so seemed just natural to use it also to save the sessions. Each of the web servers runs a separate instance of Redis, that stores a cache (the responses from the database, the processed data, etc.), and one of them is used as a central repository.

As a Redis PHP client to connect to the Redis servers, Rediska is used.

PHP Redis example

It is implemented as follows

To keep the session where you want, you need to create handlers for their storage and retrieval:

function  sess_open() {
  return true;
}
function  sess_close() {
  return true;
}
function  sess_read($id) {
  global  $Rediska;
  return  $Rediska->on(‘common’)->get(“session_”  .  $id);
}
function  sess_write($id,  $data) {
  global  $Rediska;
  $Rediska->on(‘common’)->set(“session_”  .  $id,  $data);
  $Rediska->on(‘common’)->expire((“session_”  .  $id,  86400);
}
function  sess_destroy($id) {
  global  $Rediska;
  $Rediska->on(‘common’)->delete(“session_”  .  $id);
}
function  sess_clean($max) {
  return true;
}

And to pass the names of the handlers to a function session_set_save_handler:

session_set_save_handler(‘sess_open’,  ‘sess_close’,  ‘sess_read’,  ‘sess_write’,  ‘sess_destroy’,  ‘sess_clean’);

Server connection config (configuration):

$redisca_config = array(
  ‘namespace’  =>‘XXXXX_cache’,
  ‘servers’  =>array(
    “web-1”  =>array(‘host’  =>‘xx.xx.xx.xx’,  ‘port’  =>xxxx,  ‘password’  =>‘xxxxx’,  ‘alias’  =>‘web-1’),
    “web-2”  =>array(‘host’  =>‘yy.yy.yy.yy’,  ‘port’  =>xxxx,  ‘password’  =>‘xxxxx’,  ‘alias’  =>‘web-2’),
    “common”  =>array(‘host’  =>‘yy.yy.yy.yy’,  ‘port’  =>xxxx,  ‘password’  =>‘xxxxx’,  ‘alias’ =>‘common’)// we’ll use common server to store statistics and sessions
  )
);

Creating a class instance (connecting to server):

$Rediska =  new  Rediska($redisca_config);

As you can see, in the sess_read, sess_write and sess_destroy methods we order Rediska to change the data on the server with alias ‘common’ by the key “session_”.$id.
Thus, for any queries to any web server, the user gets the same session data.
To keep track of situations where ‘common’ Redis server is not available, every web server is running continuously a script function that checks the status of Redis servers. If one or more servers are unavailable, the script overwrites the configuration file.

Summary

Redis stores all data in the memory where it can be accessed by a key. Optionally, a copy of the data can be stored to the disk. This approach provides the performance, dozens of times superior to the relational DBMSs, and simplifies data sharding.

If your project requires the services of experienced professional developers of the custom web servers and apps, if you are interested in the technologies described in this article, you can message us today to discuss your ideas with our sales persons.

Redis stores
TechnologiesJanuary 24, 2018
Have a project in mind?
We are ready to do it!
LET’S TALK ABOUT IT
Do you like this article?Please rate
5 stars
E-Learning
Hurricane In Onboarding: E-Learning That Wins Hearts And Minds
Educating new staff is a more in-deep process than simply handling corporate instructions and a to-do list if you don’t want to lose new members in a short period. Instead, it’s a way to make an excellent first impression and ensure hires both would benefit from partnering. To be precise, it’s worth considering e-learning as a powerful tool for successful employees’ onboarding.
E-commerce
How to Become the Second Aaron Jones in Digital Business
Becoming an e-commerce entrepreneur is advantageous for startups in several ways. Indeed, it is simpler and more cost-effective than establishing an office or renting spaces for brick-and-mortar shops. Moreover, online presence is open to the public, allowing to apply digital business marketing strategies for client attraction.
E-Learning
Why is it Important to Create a Multilingual E-Learning Platform?
To start a global business extension, think of your website localization and multilingual capabilities first. Creating a personalized platform for various areas will greatly increase the chances of traffic growth and customer retention. In addition, every user, who doesn’t speak your language, will appreciate your brand's efforts in providing the latest trends in web development and technical support in their native language.
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Read More