What is Redis?
Redis is an open source cache and data storage system, also known as a data structure server because of its advanced support for various data types including hashes, lists, sets, bitmaps and others. It is being used in many web apps for PHP session management, increase site search and load time on the browser.
|Setup Redis Server|
|1. What is Session?|
|2. PHP Session Handler|
|3. The Session Life Cycle|
|5. Running Redis Server|
|6. Setting Redis As Session Handler|
|7. The MySQLi Session Handler|
|8. Future of PHP Session Redis|
|9. What’s more?|
What is Session?
Sessions provides an effective way to store the data of individual users against a unique session ID, as this ID is used to preserve state information of the users between different page requests. PHP session handlers are particularly used in user/web server communicated websites, majorly ecommerce web apps and social networking sites to validate the state of the users logged-in and logged-out of the application. The default behavior of session handler fulfills all your needs in most cases, yet at times, when you want to enhance the functionalities of your apps and store session data differently.
You might also like: Using Redis Cache With custom PHP sites
PHP Session Handler
Session handler is responsible for storing and retrieving data from the saved sessions. By default, PHP uses records for this operation. Though it works fittingly well for a single server, but because session information is linked up to a single server, therefore it has some performance and scalability limitations to it.
The outer session handler provides a place for overlapped session data to reside – as they are used in different functions of the aggregate application servers – it becomes highly important when it comes to scaling PHP applications, because this session data is always called to answer queries regardless of any server accessing it.
Start Growing with Cloudways PHP Hosting Today
People Love us because we never compromise on hosting
The Session Life Cycle
When you initiate a session with session_start(), the session’s data file opens up and all the data is temporarily stored into the $_SESSION array. As the execution of script ends, the data is restored back in the file. Hence, when you implement a session variable, it is not quickly stored and goes inside the array for temporary basis. Meanwhile you can also force the session to store data immediately by calling the function session_write_close().
The function session_set_save_handler() overrides the default session handling mechanism with new functionality so that you can store the data according to your own preferences.
To create your own session-handling system, you must use these five functions including, handler_open(), handler_close(), handler_read(), handler_write(), handler_destroy(), and handler_garbage(), respectively. It is important to note that when you define these functions they should be written smartly to accept particular set of parameters, which are:
$path refers to that path address where the session information is stored as stated in the php.ini file. While the $session_name is the name of that session which is being created in the php.ini file. The main operation of this function is to initiate a new session in PHP and to allow session handler to open any needed resources. If the session is opened successfully, then it returns true otherwise returns false on failure.
This function is called when the session has finished writing something and is now free to release any unwanted resources. The function also allows handler to release that particular resource which is no longer required in the operation.
This function identifies the current session and returns a string representing that session data with respect to that session id.
$session_id is a unique identifier for the current session, while the $data is the current data of the session which must be stored. This function utilizes Boolean language to indicate the success or failure, that is true for success and false for the failed attempt.
$session_id is the unique identifier for the current session, which should be destroyed and all its data removed when this function is called.
This function is called at a particular frequency defined by the session.gc_probability configuration directive in php.ini file. It is used to remove unwanted sessions data from the expired sessions. $max_lifetime shows the time limit a session should remain active without being used, before it is considered expired.
All the above defined functions must work as described, and should give the intended functionalities for which they are developed. You can see in this section, these functions are easy to implement as they can either be deployed in a standard procedural fashion or as a method of session-handling object. After developing these functions, register your custom session handler by using the session_set_save_handler() function as follows:
session_set_save_handler($open, $close, $read, $write, $destroy, $garbage);
All the six parameters of the function ‘session_set_save_handler()’ represent a particular function that will be called to execute a specific operation. This function can be represented as a string containing the procedural function, or a method within an object that can be specified. When a method is passed as a reference within an object, an array is passed in which the first entry is the instance of that object, while the second entry is a string having the method name to call within the instance. As the session handler is successfully registered, the session_set_save_handler() function as stated above returns the Boolean true or false value for intended results.
In this tutorial, I will show you how to install Redis on a server, and then use Redis as a session handler for a PHP application on Cloudways.
You might also like: Setting up Laravel Application With Redis Cache
For the purpose of this tutorial, I assume that you have a PHP application installed on a web server. My setup is:
- PHP 7.x
I have used PHP application on a Cloudways managed PHP web hosting server because it gives a highly optimized hosting stack and ensures that you don’t get sidetracked by any server level issue. You can signup for a free account on Cloudways and can setup your server and PHP application within minutes following this GIF:
Running Redis Server
Redis server doesn’t come pre-installed on Cloudways, you have to install php redis manually. To begin installing Redis, first sign in to Cloudways Console and navigate to Server Management Tab and select the Settings and Packages Menu. Go the Packages Tab where you will find Redis installing option. Click on the Install button and your Redis server will be ready within minutes.
Setting Redis As Session Handler
In order to manage PHP session with Redis, we need to modify the values of two important variables of session that is “session.save_handler” & “session.save_path”. The default value of “session.save_handler” is “file”, so we will change it to “redis”, while the default value of “session.save_path” is “/var/lib/php5/sessions”, so we will change it to the Redis server path which is “tcp://localhost:6379” in PHP.ini file.
session.save_handler = redis session.save_path = tcp://127.0.0.1:6379
Since Cloudways doesn’t provide the functionality to edit PHP.ini file directly, so we will have to use the ini_Set() function to modify the values of session handler locally.
Now go to the Server Management Tab and open SSH Terminal. Sign in with the required credentials. Now enter the following command in your Terminal to get to your new folder:
Now type the following command to edit your index.php file.
Now your all sessions are handled by Redis, and you will just need a little PHP script to accumulate all the information in Redis session. Therefore we will be using an easy PHP script to implement counter, as each time you reload the page, it prints the number according to it and that will be incremented with the succeeding attempts. Now to start writing on this file, press the INSERT key and then remove all the existing code on the file and paste the new one, as shown below:
<?php ini_set('session.save_handler', 'redis'); ini_set('session.save_path', "tcp://localhost:6379"); //echo ini_get('session.save_path'); session_start(); $count = isset($_SESSION['count']) ? $_SESSION['count'] : 1; echo $count; $_SESSION['count'] = ++$count; ?>
Now press “Esc”, then press “:”and then type “wq” and hit Enter to save and exit the file. Now go to your Application Management Tab and click on URL to run your index.php script. When that script gets executed, it will print 1 as an output and when you will run it again, it will print 2 as an output, showing clearly that your PHP session redis is working properly.
You might also like: Setting up Yii 2 With Redis
The MySQLi Session Handler
Now you have the idea as to you can implement custom session handler using Redis, it’s time for us to move on and see how to implement custom MySQLi session handling system. For this, I will first create a class MySQLi, which will represent all the MySQL-based session. The class will contain a total of seven methods, in which there are six handlers that are specified for particular operations, as described in the previous section, while the remaining one is the constructor. However before understanding the class, let us look at the table that will store following session data as a CREATE TABLE SQL statement:
CREATE TABLE session_data (id varchar(32) primary key, data text, last_updated timestamp);
This session_data table will be used to store all our session-related information.
You might also like: PHP 5.6 Vs PHP 7 – Performance Benchmarks
Future of PHP Session Redis
Redis is touted as the perfect replacement for memcached, because it is much faster, provides scalable functionality to applications and supports different data types. That is why many web giants including Facebook, Twitter, Instagram and others have already replaced memcached with Redis session for its greater and optimized caching functionality. Moreover, many top developers and programmers from the open-source community have already started to contribute in the up-gradation of Redis in different patches.
You might also like: Using Memcached with PHP
Redis is a very comprehensive PHP session management tool and data storage system. Using it just as a PHP session handler seems only the beginning of its immersive functionalities. You can use it for executing quick searches on your site. Just save the keyword as a defined key in your Redis DB, and it will execute the function for you. Whenever a user searches on your site for that keyword, the result loads in a much faster time because it is just retrieving the output from the Redis DB. That is why Redis is the next big thing for optimizing websites, and together with Cloudways Managed PHP Hosting, we recommend it highly as it will provide you optimal results.
Launch PHP websites without the worry of Server Management.
Pre-Installed Optimized Stack with Git, Composer & SSH
Ahmed was a PHP community expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is a software engineer with extensive knowledge in PHP and SEO. He loves watching Game of Thrones is his free time. Follow Ahmed on Twitter to stay updated with his works. You can email him at firstname.lastname@example.org