PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
84: Rate Limiting and Throttling in PHP
We’ve built some pretty solid features in this course, but there's a reality check we need to face: the open internet is a chaotic place. Whether it's a poorly written loop in a client's script or a malicious bot trying to scrape your data, if you leave an endpoint wide open, someone will hammer it until your server chokes.
That's where rate limiting comes in. It's not about banning users; it's about protecting your resources. For this lesson, we're going to build a simple rate limiter for a hypothetical "Price Check" API endpoint. I don't want to use a database for this—hits to a SQL database every single time someone requests a page just to check a limit is a performance nightmare. Instead, I'm going to use Redis. It's an in-memory store, it's blazing fast, and it has a built-in "Time To Live" (TTL) feature that makes this entire process trivial.
Setting up the Redis Key Logic
The core idea here is to create a unique key for every user (or IP address) and increment a counter associated with that key. If the counter exceeds our limit within a specific timeframe, we block them. I'll keep it simple: 10 requests per minute per IP.
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$ip = $_SERVER['REMOTE_ADDR'];
$key = "rate_limit:" . $ip;
$limit = 10;
$window = 60; // seconds
$currentRequests = $redis->get($key);
if ($currentRequests >= $limit) {
http_response_code(429);
echo "Too many requests. Slow down!";
exit;
}
$redis->incr($key);
$redis->expire($key, $window);
echo "Here is your price data!";
?>
Wait, I just created a bug
I just noticed something. Look at that $redis->expire($key, $window); line. I'm calling it every single time a request comes in. That's a mistake. By resetting the expiration on every hit, I've accidentally created a "sliding window" that could potentially lock a user out forever if they keep trying to request the page every 10 seconds. The timer keeps resetting to 60, so the key never expires.
To fix this, I only want to set the expiration the very first time the key is created. I'll check if the key exists first, or better yet, use the return value of incr(). If incr() returns 1, it means this is the first request in the current window.
<?php
// ... (connection code same as above)
$currentRequests = $redis->incr($key);
if ($currentRequests === 1) {
$redis->expire($key, $window);
}
if ($currentRequests > $limit) {
http_response_code(429);
echo "Too many requests. Slow down!";
exit;
}
echo "Here is your price data!";
?>
Adding Professionalism with HTTP Headers
Just sending a 429 error is fine, but if you're building a real API, you should tell the client why they were blocked and when they can try again. This prevents them from just blindly retrying every millisecond, which only makes your server load worse.
I'll add a few custom headers. X-RateLimit-Limit tells them the max, X-RateLimit-Remaining tells them what's left, and Retry-After is a standard HTTP header that tells the client exactly how many seconds to wait.
<?php
// ... (connection and increment logic)
$ttl = $redis->ttl($key);
header("X-RateLimit-Limit: $limit");
header("X-RateLimit-Remaining: " . max(0, $limit - $currentRequests));
if ($currentRequests > $limit) {
header("Retry-After: $ttl");
http_response_code(429);
echo "Too many requests. Please try again in $ttl seconds.";
exit;
}
echo "Here is your price data!";
?>
Now we have a robust, memory-efficient throttle. We aren't touching the disk, we aren't locking tables in MySQL, and we're giving the client clear instructions on how to behave. It's a small addition, but it's the difference between a site that crashes under pressure and one that stays online.
📋 Practical Task
Build a Contact Form Submission Throttle
Create a PHP script that protects a contact form from being spammed. Instead of a general API limit, implement a "cooling off" period for form submissions.
- Use Redis to track the IP address of the user submitting the form.
- Limit the user to only 3 form submissions every 1 hour.
- If they exceed this limit, return a
429 Too Many Requestsstatus code. - Include a
Retry-Afterheader showing the remaining seconds until their window resets. - Ensure that the expiration timer is only set on the first submission of the window, not on every submission.
There are no comments for now.