1

I currently have a JavaScript that resets forms if the page is refreshed or a user presses browser back button after submitting, but if an extremely bored user defies the JavaScript and fills in and submits a form over and over again, my DB will get spammed.

I would like to prevent this from happening (perhaps by checking if there have been inserted more than 10 rows from the same user within one minute or so) but I'm kinda clueless on what to do to prevent this.

Darren
  • 13
  • 4

3 Answers3

2

Save the number of posts in a session variable.

Each time a user submits something you could do the following:

$_SESSION['postCount'] = $_SESSION['postCount'] + 1;

Then you change the whole thing to something like:

if($_SESSION['postCount'] > 2) {
  // Your code that posts to the database
  $_SESSION['postCount'] = $_SESSION['postCount'] + 1;
}

If you don't use sessions yet make sure that you start each script with session_start(); With this code no one can post something more than three times.

Jeroen de Jong
  • 337
  • 1
  • 6
0

Usually this is done with a session id/token.

This way you can check if its been submitted already and only allow it once.

Here is a similar question:

How to prevent multiple inserts when submitting a form in PHP?

Community
  • 1
  • 1
nico
  • 123
  • 1
  • 7
0

I would add a column in your table that records the timestamp of the last form submission. Then, when your page loads, declare this as a global var for your javascript.

<?php include 'connect.php';

$sql = mysqli_fetch_assoc(mysqli_query($cxn, "SELECT lastFormSubmission FROM myTable WHERE login_id = '".mysqli_real_escape_string($cxn, $_SESSION['login_id'])."'"));

$lastFormTime = $sql['lastFormSubmission'];

?>

Now declare the time as a global var:

<script type="text/javascript">
    var lastTime = '<?= $lastFormTime ?>';
</script>

Now when your form script runs, you will need to choose a threshold time of what is "too often".

//Your script
var t = new Date().getTime() / 1000; //Need time in seconds to compare with timestamp


if (t - lastTime < yourThresholdTime) {
    //don't submit form
}
  • That still doesn't solve the problem of a malicious user replaying submission data. – Mr. Llama Sep 16 '14 at 14:00
  • I think I just didn't understand the OP's question properly...will edit – The One and Only ChemistryBlob Sep 16 '14 at 14:00
  • 1
    @ChemistryBlob - Just make sure that you never leave any security up to the client (i.e. JavaScript) as it can always be tampered with. Any critical security mechanisms should be implemented at the server level (i.e. PHP) instead of client level. In this case, it would probably mean an incrementing session variable of some sort. – Mr. Llama Sep 16 '14 at 14:33