after some time so it doesn’t accumulate indefinitely, right? Currently, your code keeps the file forever even after the time window passes. We can tweak it so the file is automatically deleted when the time limit has passed. Here’s a safe way:
<?php
$limit = 30; // max requests
$time = 60; // seconds
$ip = $_SERVER['REMOTE_ADDR'];
$file = "/home/uhmn6p9kb8ir/tmp/rate_" . md5($ip); // rate limit file
echo "<!--Rate limit file: $file-->"; // for debugging
// Initialize data
$data = [
'count' => 0,
'time' => time()
];
// Read existing file if it exists
if (file_exists($file)) {
$data = json_decode(file_get_contents($file), true);
// Auto-remove file if time window has passed
if (time() - $data['time'] > $time) {
unlink($file); // delete the file
$data = ['count' => 1, 'time' => time()]; // reset counter
} else {
$data['count']++;
}
}
// Save updated data only if count > 0
if ($data['count'] > 0) {
file_put_contents($file, json_encode($data));
}
// Check rate limit
if ($data['count'] > $limit) {
$ipLog = $ip . " | " . $_SERVER['HTTP_HOST'];
$ua = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
$logFile = '/home/uhmn6p9kb8ir/logs/blocked_ips.log';
$logData = date('Y-m-d H:i:s') .
" | IP: $ipLog | UA: $ua | Blocked (Rate Limit)\n";
file_put_contents($logFile, $logData, FILE_APPEND);
http_response_code(429);
die("Too many requests. Please wait.");
}
?>






