Skip to content

Instantly share code, notes, and snippets.

@phpdave
Last active November 30, 2015 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phpdave/35bfb2c28f76085ef62e to your computer and use it in GitHub Desktop.
Save phpdave/35bfb2c28f76085ef62e to your computer and use it in GitHub Desktop.
Preventing Cross site request forgery in PHP
<?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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment