r/PHPhelp • u/csdude5 • Jul 12 '26
Using APCu instead of sessions and for rate limiting
In trying to find a way to rate limit bots server side (more complicated than I could manage with Cloudflare), I discovered APCu. Specifically:
# in Apache
RewriteCond %{QUERY_STRING} foo=([0-9]{3,}) [NC]
RewriteRule ^ - [E=HIGH_FOO:1]
RequestHeader set X-High-Foo "1" env=HIGH_FOO
# in PHP
if (isset($_SERVER['HTTP_X_HIGH_FOO'])) {
$ip = $_SERVER['REMOTE_ADDR'];
$key = 'rl_sv_' . $ip;
$count = apcu_exists($key) ? apcu_fetch($key) : 0;
if ($count >= 10) { // e.g. 10 req/min threshold
http_response_code(429);
header('Retry-After: 10');
exit('Rate limit exceeded');
}
apcu_inc($key, 1, $success, 60); // 60s TTL
}
Two questions:
- Will this work as expected to rate limit to 10 requests per 60s when foo is greater than 100?
- What's the downside?
If it matters, I'm using EasyApache on WHM/cPanel and have both PHP 5.6 and 7.4 installed. Version 5.6 is to accommodate a hosting client that refuses to update anything, and I haven't updated the other sites to 8.x yet because it'll require a bit of coding work and there's just not enough time in the day.
Follow up: if it works fine with no downside, is there a reason to not store variables here instead of relying on sessions or MySQL?
2
u/nickchomey Jul 12 '26
Surely this would be better handled at the cdn or webserver/reverse proxy level?
2
u/liamsorsby Jul 12 '26
This doesnt scale well and will only really works on a per vm basis so it will give inconsistent rate limiting functionality. Additionally, traffic has already hit your vm at thar point ao it's always better to offload rate limiting to a WAF infront of your application.