Force users to use your forms

A neat little trick to prevent pesky spam-bots from flooding your form-based applications with garbage: Use a simple token in the session to block bots from submitting data to your forms. It works like this:

1.) Generate a random token when the form is displayed, remember it in your session and put it into a hidden field of your form:

<form ...>
<?php
	/*security*/
	$my_token = create_random_string(5);   //generate the token
	$_SESSION['my_sess_token'] = $my_token;  //set it in your session
?>
<input type="hidden" name="token" value="<?=$my_token?>">
</form>

2.) Check match of those 2 tokens on every form submit and only accept submission if both are equal:

/*process form*/
if ($_POST['submit'] && $_SESSION['my_sess_token']==$_POST['token']) {
	//process your form
}

This is a handy function to create such a token:

/**
* Create a random word
*
* @param    numeric $length character lenth of the word
* @return   string random password of length
*///---------------------------------------------------------------------
function create_random_string($length=6) {
	$arr = array("1","2","3","4","5","6","7","8","9","q","w","e","r","t",
	"y","u","i","o","p","a","s","d","f","g","h","j","k",
	"z","x","c","v","b","n","m","Q","W","E","R","T","Y","U",
	"P","A","S","D","F","G","H","J","K","L","Z","X",
	"C","V","B","N","M");
	srand((float) microtime() * 1000000);
	for($i = $length; $i > 0; $i--) {
		$str .= $arr[rand(0, sizeof($arr))];
	}
	return $str;
} //function