PHP Session Management Using Redis
READ WHOLE ARTICLE
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. 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:
|
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.
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.
36 Kings Road
CM1 4HP Chelmsford
England