Struggling with spam bots slamming your contact forms on shared hosting? Do you want a simple fix without needing Redis or Memcached? You’re in the right place! Let’s dive into how you can use a lightweight flat-file approach to keep those pesky bots at bay.
Why Rate Limit Form Submissions?
Before we jump into the solution, let’s chat about why rate limiting is crucial. Imagine this: a spam bot attacks your form, sending thousands of submissions within minutes! It’s a nightmare, right? Rate limiting helps manage this by restricting how frequently a user can perform certain actions—in this case, form submissions. By limiting this rate, we can effectively block bots, giving you some peace of mind.
The 15-Line PHP Fix
This PHP solution uses a flat-file token bucket method. It tracks user actions and applies a cooldown if they exceed a set number of submissions:
$ip = hash('sha256', $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1');
$file = sys_get_temp_dir() . "/rate_$ip.json";
$now = time();
$data = file_exists($file) ? json_decode(file_get_contents($file), true) : ['count' => 0, 'time' => $now];
if ($now - $data['time'] < 60) {
if ($data['count'] >= 5) { http_response_code(429); exit('Rate limit exceeded'); }
$data['count']++;
} else {
$data = ['count' => 1, 'time' => $now];
}
file_put_contents($file, json_encode($data), LOCK_EX);
How LOCK_EX Helps
So, what’s LOCK_EX all about? Simply put, it’s a file-locking mechanism in PHP. It ensures that your file operations are safe and that no two scripts can write to the file at the same instant. This comes in handy when you deal with concurrent requests, like multiple bots trying to submit forms. This exclusive lock prevents data corruption.
Redis vs. Ephemeral Storage
Redis is great but not always available on shared hosting. Our flat-file method does the trick using the system’s temporary directory via sys_get_temp_dir(). But, it has trade-offs. The files here are ephemeral. If the server restarts, you’ll lose those files and their data. Redis, on the other hand, keeps everything in memory, which makes it faster and more durable. That’s why developers often choose Redis when they can.
Key takeaway: If you’re running on shared hosting and Redis isn’t an option, this simple flat-file approach is gold. It’s lightweight, easy, and effective to rate limit form submissions!
Conclusion
There you have it—a quick, effective way to curb spam bots using PHP and flat files. While it might not be as fancy as using Redis, it’s a superb alternative when you need something that just works without extra dependencies.
Need more innovation? Check out our article on stopping duplicate webhooks in WordPress with PHP transient locks for another creative solution to common tech problems.
For expert web development, web design, and digital marketing services, visit jis.to.

