• home
  • forum
  • my
  • kt
  • download
  • Prevent Duplicate Form Submission

    Author: 2008-08-24 10:02:27 From:

    Add this PHP code to the top of the form.php script:

    <?
    session_start();
    $secret=md5(uniqid(rand(), true));
    $_SESSION['FORM_SECRET']=$secret;
    ?>

    In the PHP code above we create a unique ID using the uniqid() function and then create a 32 character hash of this unique ID using md5() function. Next we store this unique ID in the session for later use in the form-exec.php script. Remember to use a different session variable for each form.
    Then add a hidden field anywhere in your form:

    <html>
    <input type="hidden" name="form_secret" id="form_secret" value="<?php echo $_SESSION['FORM_SECRET'];?>" />
    </html>


    Handling form submission

    Compare the value of the hidden field with the value stored in the session. If the values match, process the form data. After processing the form data unset the value stored in the session. Now if the user refreshes the page, the form processing code will be skipped. See the sample code below.

    <?
    //Retrieve the value of the hidden field
    $form_secret=$_POST['form_secret'];
    if(isset($_SESSION['FORM_SECRET'])) {
    if(strcasecmp($form_secret,$_SESSION['FORM_SECRET'])===0) {
    /*Put your form submission code here
    After processing the form data,
    unset the secret key from the session
    */

    unset($_SESSION['FORM_SECRET']);
    }else {
    //Invalid secret key
    }
    }else {
    //Secret key missing
    echo 'Form data has already been processed!';
    }
    ?>

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      Ad Management (4)
      Calendars (3)
      Chat Systems (7)
      Content Management (6)
      Cookies and Sessions (8)
      Counters (8)
      Database Related (8)
      Date and Time (9)
      Development (6)
      Discussion Boards (7)
      E Commerce (6)
      Email Systems (9)
      Error Handling (5)
      File Manipulation (10)
      Flash and PHP (4)
      Form Processing (8)
      Guestbooks (12)
      Image Manipulation (21)
      Installing PHP (7)
      Introduction to PHP (24)
      Link Indexing (8)
      Mailing List Management (9)
      Miscellaneous (54)
      Networking (8)
      News Publishing (9)
      OOP (24)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (6)
      Postcards (1)
      Randomizing (14)
      Redirection (11)
      Searching (9)
      Security (29)
      Site Navigation (16)
      User Authentication (14)
      WAP and WML (7)
      Web Fetching (8)
      Web Traffic Analysis (15)
      XML and PHP (16)

    New

    Hot