Using random numbers to prevent users from reloading a page

An easy way to prevent users from reloading a page is to seed each form with a random number and simultaneously store this number in your database. To do this, you need the function db_check_crea () that we have defined in section 2.2.5 above. The following make sure that a table of such random numbers exists and stores for each query such a number in the database.

    db_check_crea ("cookies","cookie INT,userid VARCHAR(64),ctime DATETIME,
                   INDEX(cookie),INDEX(userid)");
    mt_srand((double)microtime()*1000000+377);  
    $nextcookie=mt_rand();
    mysql_query ("INSERT INTO cookies SET cookie=$nextcookie,userid=\"$USERID\"");

For each form that you generate, add the line

<INPUT TYPE=HIDDEN NAME=\"COOKIE\" VALUE=\"$nextcookie\">

Before you evaluate a form you check whether the following function returns a positive value.

function test_cookie () {
  global $USERID,$COOKIE;
  mysql_query ("DELETE FROM cookies WHERE ctime<NOW()");
  mysql_query ("UPDATE cookies SET ctime=NOW() WHERE cookie=\"$COOKIE\" AND userid=\"$USERID\"");
  return (mysql_affected_rows ());
}

If it does not, you have detected somebody who tries to send the same form a second time.



Oliver Kirchkamp 2013-04-15