Testimonials

Martin Martinez
Multi-Programming Solutions team has been there for me every step of the way for this huge project! Martin Martinez
Luke Mitchell/Managing Consultant/Reach Students
Multi-Programming Solutions delivered on time, within budget and precisely to the brief – everything a client could wish for. Luke Mitchell, Managing Consultant, Reach Students
Dane Westo
I have been working with multiprogr for about 4 months now. The programming and designing has been second to none. I have used several developers and designers over a 3 year period. multiprogr is the Dane Westo
Matthew Campbell
Fantastic job, with intuitive understanding of functionality and proactive recommendations. Matthew Campbell
Benjamin Melki, Kaeria CEO
Excellent job again. Benjamin Melki, Kaeria CEO
Ken Kimble
This team is awesome! Ken Kimble

Blog

PHP session management using Redis

September 2016, 06
php sessions in redis


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.

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. 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 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 (http://rediska.geometria-lab.net/) is used.
 

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.



Other articles

Thank you for getting in touch!

We appreciate you contacting us and will try to get back to you within a few hours. Have a great day ahead!