file not being deleted after its expiry time passes
03:47 29 Jun 2026

I'm trying to make a rate limiting function that prevent users from using specific forms when they reach a certain threshold. The limit will get reset after a certain amount of time. When a user submits a request, a file with their IP will get created into a cache folder and the amount of requests is inside the file.

The rate limiting works except the file doesn't get deleted after the specified amount of time passes.

rate_limiter.php

= $requests_limit) {
            global $reached_limit;
            echo "";
            $reached_limit = true;
            header("Location: /", 423, true);
        } elseif (!$reached_limit) {
            $new_amount_requests++;
            ftruncate($fp, 0);
            fwrite($fp, $new_amount_requests) or
                die("Failed to write amount of requests");
        }
    }

    if (
        file_exists($file_name) &&
        time() - $start_time >= time() + $limit_expiry
    ) {
        unlink($file_name);
    }
}

?>

index.php



How the code works:

When the user hasn't submitted a request yet, there would be no file in the cache. The function will check that with the file_exists function. If it returns false, it will create a file with the users IP, the timer will start, and it will write the default amount of requests which is "1" into the file.

After that, when the user submits another request, the function will check if there is a file or not (in the second if statement). If there is, it will check the amount of requests inside. If they exceed the maximum limit (3 in this case), it will change reached_limit to true. If it didn't reach the maximum limit, it will read the value inside the file, clear the file, and write the new value into the file until it reaches the limit. At the end, if the timer exceeds the limit_expiry integer in the function, it will delete the file which resets the limit.

php forms