Business, Tech, Life, and Whatever else

Secure web forms with tokens

by Eric Barnes on January 8, 2009

In this post I will show you how to secure your web forms using tokens. This is a common practice and prevents people from using external services to pound your form with fake data.

The first step is to create your form. Here is a simple one as an example:

<form action="test.php" method="post" name="test">
<input name="email" type="text" />
<input name="pass" type="password" />
<input name="token" type="hidden" value="<?php echo $_SESSION['token']; ?>" />
</form>

Notice this form has a “token” field as a hidden field. This field will hold the actual token.

Now let’s look at the php portion.

session_start();
function generateToken($seed='mysupersecretkey')
	{
		$token = md5($seed.mktime());
		$_SESSION['token']=$token;
		return $token;
	}
generateToken();

//validate the form
if(isset($_POST['email']) && isset($_POST['pass']) && isset($_POST['token']))
{
	if($_POST['token'] != $_SESSION['token'])
	{
		die('Token is invalid');
	}
	//process the rest of form here
}

Here is the final full file: View Full Code

<?php
session_start();
function generateToken($seed='mysupersecretkey')
	{
		$token = md5($seed.mktime());
		$_SESSION['token']=$token;
		return $token;
	}
generateToken();

//validate the form
if(isset($_POST['email']) && isset($_POST['pass']) && isset($_POST['token']))
{
	if($_POST['token'] != $_SESSION['token'])
	{
		die('Token is invalid');
	}
	//process the rest of form here

}
?>

<form action="test.php" method="post" name="test">
<input name="email" type="text" />
<input name="pass" type="password" />
<input name="token" type="hidden" value="<?php echo $_SESSION['token']; ?>" />
</form>

Hopefully this will help you out when creating your web forms and if you have any comments please post them below.

You May Also Be Interested In...

Restore Lost Form Fields
July 16, 2009

68 Classifieds and Google Apps
February 16, 2009

Wordpress and Google Apps
December 21, 2008

Import Listings into 68 Classifieds
August 18, 2009

Subscribe Now

If you enjoyed this post, you will definitely enjoy my others. Subscribe to the feed to get instantly updated for those awesome posts soon to come.


blog comments powered by Disqus