Below is an example of how to prevent cross-site request forgery in PHP. Basically you create a form token tied to the user’s session. When the form is submitted we verify that they have a token and that its the token we issued to the user. If it’s not we don’t process the form and echo out an error message.

<?PHP
session_start();
//Include this PHP file for generating random strings: https://github.com/IcyApril/CryptoLib/blob/master/src/CryptoLib.php
require 'CryptoLib.php';
//Generate a form token that we'll use to authenticate that this was a form we created
if(!isset($_SESSION['FormAuthenticatorToken']))
{
$_SESSION['FormAuthenticatorToken'] = IcyApril\CryptoLib::randomString(50);
}
/*Form submission handler*/
if(isset($_POST['FormAuthenticatorToken']))
{
if($_POST['FormAuthenticatorToken'] !== $_SESSION['FormAuthenticatorToken'])
{
echo 'You submitted a form that was not from this site';
}
else
{
//process the form
}
}
?>
<form action="#" method="POST">
<input type="hidden" name="FormAuthenticatorToken" value="<?= $_SESSION['FormAuthenticatorToken'] ?>" />
Name:<input type="text" name="Name"/><br/>
Email:<input type="text" name="Email"/><br/>
<input type="submit"/>
</form>

view raw
CSRF.php
hosted with ❤ by GitHub