Search code examples
phphtmlsubmit-button

How to make sure Submit button isn't abused to run php code repeatedly


<form action="test.php" method="POST">
HTML CODE
</form>
<button type="submit" name="test" value="1">Buy</button>

 ---> test.php

if(isset($_POST['test'])) {

PHP CODE

}

I've included test.php above that html form, but when I click on submit over and over again before the page runs the php code and loads the whole page again, it runs the php code as many times as I clicked

How do I make sure that one cannot abuse 'submit' button over and over to run the php code again and again? I only want the first click to be considered.

Can someone help please.


Solution

  • Good way would be to include some kind of captcha. I personally prefer Recaptcha from Google (https://www.google.com/recaptcha/intro/v3beta.html)

    It does not show up at all and you can verify it for any incoming request.

    To get it started embed the following JS in your html:

    <script src='https://www.google.com/recaptcha/api.js'></script>

    and then replace your submit button:

    <button
      class="g-recaptcha"
      data-sitekey="YOUR_PUBLIC_SITE_KEY"
      data-callback="YourOnSubmitFn">
    Buy
    </button>
    

    Last thing remaining is to check from php if the code was right :)

    POST 'https://www.google.com/recaptcha/api/siteverify' with secret, response and remoteip -> then allow the user to the function, else just abort