PHP Classes

Lightweight PHP Form Token Validation: Generate and validate form tokens served via AJAX

Recommend this page to a friend!
  Info   View files Example   View files View files (4)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not yet rated by the usersTotal: 178 All time: 8,723 This week: 90Up
Version License PHP version Categories
formtoken 1.0.0Public Domain7PHP 5, Security
Description 

Author

This class can be used to generate and validate form tokens that are created dynamically via JavaScript and a server-side PHP script.

It can generate a token string that is valid only only once. The token value is added to the page dynamically as an hidden form input so screen scrappers are not able to find it because usually they do not run JavaScript code, thus reducing the risk of automated attacks.

The class can also verify if the previously generated form token is the same to prevent form tampering.

Picture of Ray Paseur
  Performance   Level  
Name: Ray Paseur is available for providing paid consulting. Contact Ray Paseur .
Classes: 8 packages by
Country: United States United States
Age: 73
All time rank: 2240311 in United States United States
Week rank: 131 Up15 in United States United States Up
Innovation award
Innovation award
Nominee: 5x

Winner: 1x

Example

<?php // demo_FormToken.php
/**
 * A client side script that creates an AJAX request for a form token
 * This script injects the form token into the request variables
 */
error_reporting(E_ALL);
require_once(
'class_FormToken.php');
session_start();


// IF THERE IS A POST-REQUEST
if (!empty($_POST))
{
   
$status = FormToken::check();
    if (!
$status) echo "Attack! Run like hell!";
    if (
$status) echo "Success! Trust this client.";
    exit;
}


$html = <<<EOF
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<title>A Variable Form Token Example</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>

<script>
$(document).ready(function(){
    $.get("server_FormToken.php", function(response){
        var json = JSON.parse(response);
        var myForm = document.forms['my_form'];
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = json.name;
        input.value = json.token;
        myForm.appendChild(input);
    });
});
</script>

</head>
<body>

<form name="my_form" method="post">
<input type="submit" value="Verify Token" />
</form>

</body>
</html>
EOF;

echo
$html;


Details

Class FormToken This is a lightweight implementation of the dynamic Form Token strategy that helps to mitigate "screen scraper" automation and Cross-Site Request Forgeries (CSRF). More on the risks and attack methods can be found in these links: http://phpsecurity.org/ch02.pdf (Old but still useful) https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet It is axiomatic that today (2019) any web site of value should be using HTTPS protocols, and not HTTP. You must use HTTPS for the Form Token to provide meaningful safety. Most PHP installations will give you a data point, such as $_SERVER['REQUEST_SCHEME'] to test for HTTPS. You can rewrite any non-https requests, or simply discard these requests. It is also important to use the right PHP session management. If your PHP session data escapes into the wild it would be computationally trivial to extract the form token name and value, and these values could be inserted into an HTML form. Good info: http://php.net/manual/en/features.session.security.management.php PHP offers a built-in CSRF mitigation function, output_add_rewrite_var() but the effect is to place a hidden input control into the HTML forms. This leaves the script vulnerable to scraping. http://php.net/manual/en/function.output-add-rewrite-var.php To use Class FormToken, (1) Install the Class and require it in any PHP script that uses forms, (2) Install the server_FormToken.php script, (3) Follow the JavaScript/jQuery example shown in demo_FormToken. Originally published, with discussion, here: https://www.experts-exchange.com/articles/28802/

  Files folder image Files  
File Role Description
Plain text file class_FormToken.php Class Class_FormToken source
Accessible without login Plain text file demo_FormToken.php Example Demonstration Script
Accessible without login Plain text file readme_FormToken.txt Doc. readme text file
Accessible without login Plain text file server_FormToken.php Appl. Server-side token generator

 Version Control Unique User Downloads Download Rankings  
 0%
Total:178
This week:0
All time:8,723
This week:90Up