<?php
class FormSubmissionLimiter {
private $limit;
private $window_size;
private $submissions = [];
private $dry_run = false;
public function __construct(int $limit, int $window_size, bool $dry_run = false) {
$this->limit = $limit;
$this->window_size = $window_size;
$this->submissions = [];
$this->dry_run = $dry_run;
}
public function isAllowed(string $form_id): bool {
$now = time();
// Remove submissions outside the window
$this->submissions = array_filter($this->submissions, function ($submission) use ($now, $window_size) {
return $now - $submission['timestamp'] < $window_size;
});
// Check if the limit is exceeded
if (count($this->submissions) >= $this->limit) {
if ($this->dry_run) {
error_log("Dry run: Submission limit exceeded for form $form_id.");
return false; // Dry run: don't actually block
} else {
throw new Exception("Submission limit exceeded for form $form_id.");
}
}
return true;
}
public function submit(string $form_id, array $data): bool {
if (!$this->isAllowed($form_id)) {
return false;
}
// Log the submission
$this->submissions[] = [
'timestamp' => time(),
'data' => $data,
];
return true;
}
public function reset() {
$this->submissions = [];
}
}
// Example Usage (for testing - remove in production)
/*
$limiter = new FormSubmissionLimiter(5, 60); // Limit 5 submissions in 60 seconds
try {
for ($i = 0; $i < 10; $i++) {
if ($limiter->isAllowed('my_form')) {
$limiter->submit('my_form', ['field1' => 'value' . $i, 'field2' => 'data' . $i]);
echo "Submission successful for form my_form\n";
} else {
echo "Submission blocked for form my_form\n";
}
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
$limiter->reset();
*/
?>
Add your comment