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
How to Make Your Educational Application Successful?
Every year the education system is accompanied by new requirements for teaching methods, taking a course on increasing material memorability and its practical application to modern realities. The use of ambitious educational application software has caused a technological revolution in schools and universities, which has also impacted the quality of students' knowledge. But to become a unicorn in such a competitive and flexible IT environment, developers will have to create a tool with great functionality in a short time. This article will talk about how to do it [...]
PWA
How to Brainly Improve Your Progressive Web App: Costs, Timeframes, Tips & Tricks, and Expert Opinion
The increased use of mobile and web apps during the pandemic has rapidly transformed into a change in consumer behavior. People can no longer imagine life without their smartphones: they live in a network of interconnected, valuable applications that change one's life for the better every day. In this article, you will find out why it is essential to finally launch your own app or improve existing ones in 2022 and how to do it.
E-commerce
Ecommerce Shops Design Tendencies that Win the Competition
There is an opinion that if your business is not online, it stands still. In the realities of today's world, the digital marketplace is dominant, allowing you to expand your client base, increase revenue, and impact brand reputation. But to make a website that sells and achieves your goals by unlocking your store's potential, you must plan and think about your content and products for an effective presentation on the net. Retail underwent a severe but rapid disintegration with the onset of the Covid-19 pandemic. It has been replaced by eCommerce, which has rapidly bridged the gap between client and merchant, making the digitized economy of the future. For example, Walmart's sales grew by 97% in 2020. Smaller entrepreneurs such as B-Wear Sportswear also saw a triple income increase in contrast to the year before. But the impressive luck of these sites is due to their excellent eCommerce UX design: visitors have longer sessions on them than on other sites, which is one of the many decisive factors in making profitable campaigns [...]
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