mkaz solutions log » home

How to Fix Double Posting

Date: Jul 3, 2007

You see the following on order forms all the time >> “press the button only once or we may charge you double”

This is just laziness on the developers, there are a few easy techniques to avoid double processing a form. Plus if you have ever watched my mother-in-law use a computer, there is a fine line between clicking once and double (or even triple) clicking.

Here’s one way to solve double posting. The process is:


Example Code in PHP

Here’s some example code using this technique in PHP

First you need to setup your transactions table:

  CREATE TABLE transactions (
         transaction_key    varchar(24),
         UNIQUE INDEX uki (transaction_key)
  );

A PHP function to get a unique id, abstracted in case you want to change it later, we use smarty functions at work, so this was created as a smarty tag:

  function get_transaction_key() {
      return uniqid('', true);
  }

The main function which checks if the key has been used before:

  function check_transaction_key($key) {
      $return_value = db_insert(" INSERT INTO transactions (transaction_key) VALUES ('$key') ");
      if ($return_value === false) { return false; }
      else { return true; }
  }

Your PHP+HTML Template Script:

  <form>
      <input type="hidden" name="txn_key" value="<?php get_transcaction_key() ?>">
      ... extra form stuff...
  </form>

Your PHP Form Process Script:

  if (check_transaction_key($_REQUEST['txn_key'])) {
        ... continue processing form ...
  }
  else {
    // duplicate entry, dont insert
  }

NOTE: The sample code above should not be considered best practices. Your PHP+HTML should be in a nice template and you should scrub all your submitted variables before doing anything with them.

Next up: The annoying please do not include spaces in credit card fields