Last active
November 30, 2015 20:51
-
-
Save phpdave/35bfb2c28f76085ef62e to your computer and use it in GitHub Desktop.
Preventing Cross site request forgery in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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