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.
