How to Use Redis to Implement PHP Rate Limiting on Ubuntu 20.04 (Article Sample)
Redis (Remote Dictionary Server) is an open-sourced in-memory database. It's a data-structured storage system that runs on a server's RAM, which is many times quicker than even the fastest SSD (SSD). As a result, Redis is very responsive and hence appropriate for rate restriction.
A mechanism called rate limitation limits the number of sessions a user may request a resource from a server. Many services use rate limits to stop service abuse, like when a user tries to overrun a server with too many people.
How to Use Redis to Implement PHP Rate Limiting on Ubuntu 20.04
Introduction
Redis (Remote Dictionary Server) is an open-sourced in-memory database. It's a data-structured storage system that runs on a server's RAM, which is many times quicker than even the fastest SSD (SSD). As a result, Redis is very responsive and hence appropriate for rate restriction.
A mechanism called rate limitation limits the number of sessions a user may request a resource from a server. Many services use rate limits to stop service abuse, like when a user tries to overrun a server with too many people.
For example, when using PHP to develop a public API (application programming interface) for your web application, rate restrictions are required. The rationale for this is that when you expose an API to the public, you'll want to limit how many times an individual may repeat an activity in a certain amount of time. Users that have no authority over your system may put it to a standstill.
This allows your application to function smoothly by rejecting user requests that exceed a set limit. If you have a large number of clients, rate limitation imposes a fair-use policy that permits each user to access your application at fast speeds. Rate limiting may also help you save money on bandwidth by lowering congestion on your server.
By tracking user activity in a database like MySQL, it would be possible to create a rate-limiting program. However, since such data should be downloaded from disk and evaluated against the defined limit, the final result may not be scalable when multiple people contact the system. Not only is this inefficient, but relational database management solutions were not built for this.
Redis is a good choice for making a rate limiter because it works as an in-memory database and has been proven to be reliable for this.
requirements
Installing the Redis Library for PHP
Start by changing the index of your Ubuntu server package repository. Install the php-redis extension after that. This is a package that makes it possible to use Redis in PHP programs. Run the following instructions to do this:
sudo apt update
sudo apt install -y php-redis
To load the php-redis library, restart the Apache server:
sudo systemctl restart apache2
Your next step is to update the information in your software index and install the Redis library for PHP. Then you will create a PHP resource that restricts access based on a user's IP address.
Building a PHP Web Resource for Rate Limiting
In this step, you'll create a test.php file in your web server's root directory (/var/www/html/). This file will be open to the public, and users will be able to launch it by typing its URL into a web browser. However, later in this book, you'll use the curl command to see if you can get to the resource you want to use.
Users may access the sample resource file three times in a 10-second span. Users who try to go over the limit will get an error message that says they've been rate limited, and they'll have to stop.
This file's primary functionality is strongly dependent on the Redis server. The PHP code in the file creates a key on the Redis server depending on the user's IP address when the user accesses the resource for the first time.
The PHP code will attempt to match the user's IP address with the keys saved in the Redis server and increase the value by one if the key exists when the user returns to the resource. The PHP code will keep checking to see if the new value has reached the maximum amount.
After 10 seconds, the Redis key, which is based on the user's IP address, will expire, and tracking the user's visits to the web resource will begin again.
To begin, open the test.php file in /var/www/html/test.php:
sudo nano /var/www/html/test.php
To initialize the Redis class, input the following information: Remember to set the REDIS PASSWORD to the correct value:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('REDIS_PASSWORD');
Redis->auth supports Redis server plain text authentication. This is ok if you're working locally (through localhost), but if you're dealing with a distant Redis server, SSL authentication is recommended.
Next, in the same file, set the following variables to their default values:
. . .
$max_calls_limit = 3;
$time_period = 10;
$total_user_calls = 0;
Then, to get the IP address of the person that requested the web page, add the following code:
. . .
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$user_ip_address = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$user_ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$user_ip_address = $_SERVER['REMOTE_ADDR'];
As a demonstration, this code logs users' actions by their IP addresses. If you have a protected resource on the server that needs authentication, you could also track users' actions by their usernames or access tokens.
In this case, each user that logs into your system will be assigned a unique identification (for example, a customer ID, developer ID, vendor ID, or even a user ID). (Remember to use these IDs instead of the $user_ip address if you set this up.)
For the purposes of this tutorial, the user's IP address is sufficient to demonstrate the notion. Add the following code block to your file once you've gotten the user's IP address from the preceding code snippet:
. . .
if (!$redis->exists($user_ip_address)) {
$redis->set($user_ip_address, 1);
$redis->expire($user_ip_address, $time_period);
$total_user_calls = 1;
} else {
$redis->INCR($user_ip_address);
$total_user_calls = $redis->get($user_ip_address);
if ($total_user_calls > $max_calls_limit) {
echo "User " . $user_ip_address . " limit exceeded.";
exit();
}
}
echo "Welcome " . $user_ip_address . " total calls made " . $total_user_calls . " in " . $time_period . " seconds";
Save and close the /var/www/html/test.php file after you've done modifying it.
On t
Other Topics:
- Critical Review of YOOXDescription: Critical appraisal is defined as evaluating literature systematically and methodologically to ascertain its reliability and significance in its context of use (Hong and Pluye, 2019). Insofar, it's regarded as a crucial and integral process for evidence-based practice since it helps company decision-makers ...8 pages/≈2200 words| 6 Sources | Other | Creative Writing | Article |
- Why i want to work in America Creative Writing ArticleDescription: If I were given a chance to work abroad I would definitely choose to work in Australia. I can say without a second thought that I have always dreamt of visiting Australia not as a tourist but a professional worker who is paid by the hour one has worked. Life is dynamic and as such...1 page/≈275 words| No Sources | Other | Creative Writing | Article |
- Virtual vs traditional home staging Creative Writing ArticleDescription: Homeowners and sellers have a lot to consider before buying or selling a home. This business idea needs to look into the expenses involved, time frame and means of conducting the sale. There are two home staging ways; one is the traditional way while the second is virtually done....1 page/≈550 words| No Sources | Other | Creative Writing | Article |