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


Sometimes the user can press twice, and the post is thrown twice.

Is there a solution to stop other than paying attention if there is already a post with a title and content ?

There are several solutions to this problem:

  1. < Strong> Use Javascript button to disable form deposits when posted. To do this, it is very easy to submit the form without actually clicking the button, and it will not work with javascript disabled people. I will definitely not recommend this method.

    Example:

      & lt; Script language = "javascript" & gt; & Lt ;! - Disable the FunctionBitButton () {// You can fill the empty space :)} - & gt; & Lt; / Script & gt; & Lt; Form action = "foo.php" method = "post" & gt; & Lt; Input type = "text" name = "bar" /> & Lt; Input type = "submit" value = "save" onclick = "disableSubmitButton ();" & Gt; & Lt; / Form & gt;  
  2. Set the session variable (for example $ _SESSION ['posttimer']) from the current timestamp on the post. Before actually check the form in PHP, check if $ _SESSION ['posttimer'] variable exists and check for a certain timestamp difference (IE: 2 seconds). In this way, you can easily double submit.

    Example:

      // form.html & lt; Form action = "foo php" method = "post" & gt; & Lt; Input type = "text" name = "bar" /> & Lt; Input type = "submit" value = "save" & gt; & Lt; / Form & gt; // if foo.php (isset ($ _ POST) & amp; blank ($ _ POST) {if (isset ($ _ session ['poster']) {if (((time () - $ _SESSION [' Posttimer ']) & lt; = 2) {// less than 2 seconds} since last post and {// more than 2 seconds since last post}} $ _SESSION [' poster '] = time ();  
  3. Include a unique token on each POST. In this case, you want to set a session variable for the token To include the token and then submit the token in the form. After the form is submitted, you will receive the token When the submitted token does not match token in your session, the form has been resubmitted and it should be declared invalid.

    Example:

    < Pre> // form.php & lt ;? php // Clearly it may be anything you want, unless it's unique $ _SESSION ['token'] = MD5 (session_id). Time ());? & Gt; form action = "foo.php" method = "post" & gt; Input type = "hidden" name = "token" value = "& lt ;? Php echo $ _SESSION ['token']? Input type = "text" name = "bar" /> gt; input type = "submit" value = "save" />

Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -