The principle is to generate a random string in the session. Submitting the form later validates the string. You can prevent others from writing form to cheat submissions, repeat submissions, or double click Submit.
token.php
<?php
/*
* Created on 2013-3-25
*
* To change the template for this generated file go
* Window-preferences-phpeclipse-php-code Templates
*/
function GetToken ($len = $md 5 = true) {
# Seed Random number generator
# only needed for PHP versions prior to 4.2
Mt_srand (Double) microtime () * 1000000);
# Array of characters, adjust as desired
$chars = Array (
' Q ',
'@',
' 8 ',
' Y ',
'%',
'^',
' 5 ',
' Z ',
'(',
' G ',
'_',
' O ',
'`',
' S ',
'-',
' N ',
' < ',
' D ',
'{',
'}',
'[',
']',
' H ',
';',
' W ',
'.',
'/',
'|',
':',
' 1 ',
' E ',
' L ',
' 4 ',
' & ',
' 6 ',
' 7 ',
'#',
' 9 ',
' A ',
' A ',
' B ',
' B ',
'~',
' C ',
' d ',
' > ',
' E ',
' 2 ',
' F ',
' P ',
' G ',
')',
'?',
' H ',
' I ',
' X ',
' U ',
' J ',
' K ',
' R ',
' L ',
' 3 ',
' t ',
' M ',
' N ',
'=',
' O ',
'+',
' P ',
' F ',
' Q ',
'!',
' K ',
' R ',
' s ',
' C ',
' m ',
' T ',
' V ',
' J ',
' U ',
' V ',
' W ',
',',
' X ',
' I ',
'$',
' Y ',
' Z ',
'*'
);
# Array Indice friendly number of chars;
$numChars = count ($chars)-1;
$token = ';
# Create Random token at the specified length
for ($i = 0; $i < $len; $i + +)
$token. = $chars [Mt_rand (0, $numChars)];
# Should token be run through MD5?
if ($MD 5) {
# Number of char chunks
$chunks = Ceil (strlen ($token)/32);
$MD 5token = ';
# Run each chunk through MD5
for ($i = 1; $i <= $chunks; $i + +)
$MD 5token. = MD5 (substr ($token, $i * 32-32, 32));
# Trim The token
$token = substr ($md 5token, 0, $len);
}
return $token;
}
?>
form.php
<?php
Include_once ("token.php");
$token = GetToken ();
Session_Start ();
$_session[' token ' = $token;
?>
<form action= "action.php" method= "POST"
<input type= "hidden" name= "token" value= "<?= $token?>"/>
<!--other input submit-->
</form>
action.php
<?php
Session_Start ();
if ($_post[' token '] = = $_session[' token ']) {
unset ($_session[' token '));
echo "This is a normal submission request";
}else{
echo "This is an illegal submission request";
}
?>