Charles
Charles

Reputation:

How do I limit form submission rates and inputs in PHP?

  1. How do I make it so people can't use an input more than once every minute?

  2. How can I remove the ability to put any non-char/number characters into a submit thing? Alphabet will work and so will numbers but +,-,), etc, won't?

Upvotes: 0

Views: 5731

Answers (4)

Markus Malkusch
Markus Malkusch

Reputation: 7878

Use the token bucket algorithm with a session storage for rate limiting. Luckily I implemented that for you: bandwidth-throttle/token-bucket

use bandwidthThrottle\tokenBucket\Rate;
use bandwidthThrottle\tokenBucket\TokenBucket;
use bandwidthThrottle\tokenBucket\storage\SessionStorage;

$storage = new SessionStorage("myForm");
$rate    = new Rate(1, Rate::MINUTE);
$bucket  = new TokenBucket(1, $rate, $storage);
$bucket->bootstrap(1);

if (!$bucket->consume(1, $seconds)) {
    http_response_code(429);
    header(sprintf("Retry-After: %d", floor($seconds)));
    exit();
}

Upvotes: 1

Mark
Mark

Reputation: 6228

You can use PHP sessions. And then check against the session value each time a form is submitted to see if it has been more than X seconds. Example

if (!isset($_SESSION['last_submit']))
    $_SESSION['last_submit'] = time();

if (time()-$_SESSION['last_submit'] < 60)
    die('Post limit exceeded. Please wait at least 60 seconds');
else
    $_SESSION['last_submit'] = time();

You'll want to use regular expressions. Since this is question tagged beginner, understanding how they work might be out of your scope. But this function will strip out all non letter and digit characters:

$string = ereg_replace('[^A-Za-z0-9]','', $string);

This example:

$string = 'sdrw%@#-14345';
$string = ereg_replace('[^A-Za-z0-9]','', $string);
echo $string;

will produce "sdrw14345"

Upvotes: 5

David Wolever
David Wolever

Reputation: 154672

With regard to your second question, you'll need to do that using HTML and JavaScript... And there are lots of resources for that online: http://www.google.com/search?q=restrict+characters+javascript

Of course, you can't trust that the end-user hasn't disabled JavaScript, so you'll want to verify that, when your PHP gets the data back, it's still valid... Something like:

if (preg_match("[^a-zA-Z0-9]", $input)) {
    error("The input has invalid characters in it!");
}

Upvotes: 0

David Wolever
David Wolever

Reputation: 154672

Limiting "stuff form a user" is a very imprecise science: it's very, very difficult to figure out where a request came from. You could use the remote user's IP address, but then you risk limiting legitimate requests if there are a bunch of users behind a NAT. You can do it by cookie (set a cookie with a TTL of 1 minute, then don't let them submit if that cookie is set), but it's possible (read: easy) to simply delete that cookie.

Does that help? Do you want more information about using either IP or cookie?

Upvotes: 0

Related Questions