<?php
session_start
();
echo <<<HTML
<html>
    <head>
        <title>CSRF Defense (horrible)</title>
    </head>
HTML;
if(isset(
$_POST['name']))
{
    
//Form Submitted, Check CSRF
    /*
     A better check would be
     if(
        isset($_POST['csrf']) && strlen($_POST['csrf']) == 32 &&
        isset($_SESSION['csrf']) && strlen($_SESSION['csrf']) == 32 &&
        $_POST['csrf'] == $_SESSION['csrf']
        )
    */
    
if ($_POST['csrf'] == $_SESSION['csrf'])
    {
        
//CSRF good, regenerate token to prevent re-use
        
$_SESSION['csrf'] = md5(time());
        
        
//CSRF good, print message if data is valid
        
if (strlen($_POST['name']) > && strlen($_POST['name'] < 26))
        {
            echo 
'<body bgcolor="green">';
            echo 
"Hello " htmlentities($_POST['name']) . " thank you for submitting a form";
            echo 
'</body></html>';
        }else
        {
            echo 
'<body bgcolor="blue">';
            echo 
"That name looks fishy";
            echo 
'</body></html>';
        }
    }else
    {
        echo 
'<body bgcolor="red">';
        echo 
"CSRF Failed!";
        echo 
'</body></html>';
    }    
}else
{
    echo 
'<body bgcolor="white">';
    
    
//This isn't random! Generate a random token with a sufficient amount of entropy.
    // Perhaps md5(mt_rand() . mt_rand() . mt_rand() . mt_rand()); which should
    //   provide 128 bits of entropy. Running less entropy through a hashing function
    //   than it has bits leaves attackers with another route, they can attack your
    //   inputs rather than simple MD5 collision.
    //   http://en.wikipedia.org/wiki/Random_number_generator_attack
    // Another option may be:
    //  $fp = fopen('/dev/random', 'r'); $csrf = md5(fread($fp, 128)); fclose($fp);
    
$csrf md5(time());
    
$_SESSION['csrf'] = $csrf;
    echo <<<FORM
<form method="post">
    Name: <input type="text" name="name" maxlen="25">
    <input type="hidden" name="csrf" value="
$csrf">
    <input type="submit">
</form>
</body>
</html>
FORM;
}