PHP Classes

File: demo_FormToken.php

Recommend this page to a friend!
  Classes of Ray Paseur   Lightweight PHP Form Token Validation   demo_FormToken.php   Download  
File: demo_FormToken.php
Role: Example script
Content type: text/plain
Description: Demonstration Script
Class: Lightweight PHP Form Token Validation
Generate and validate form tokens served via AJAX
Author: By
Last change:
Date: 5 years ago
Size: 1,224 bytes
 

Contents

Class file image Download
<?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;