Last active
December 14, 2015 01:39
-
-
Save iNaD/5007601 to your computer and use it in GitHub Desktop.
Simple snippet to harden your forms against CSRF (see http://en.wikipedia.org/wiki/Cross-site_request_forgery).
This file contains hidden or 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 | |
function create_csrf_field() | |
{ | |
$field_hash = hash('sha256', time().'some_salt'); | |
$hash = hash('sha256', 'some_salt'.time().rand(0,10)); | |
$_SESSION['csrf_field'] = $field_hash; | |
$_SESSION['csrf_hash'] = $hash; | |
return '<input type="hidden" name="'.$field_hash.'" value="'.$hash.'">'; | |
} | |
function check_csrf() | |
{ | |
if(isset($_SESSION['csrf_field']) && isset($_SESSION['csrf_hash']) && isset($_POST[$_SESSION['csrf_field']])) | |
{ | |
if($_POST[$_SESSION['csrf_field']] == $_SESSION['csrf_hash']) | |
return true; | |
} | |
return false; | |
} |
This file contains hidden or 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 | |
require_once dirname(__FILE__).'/csrf.php'; | |
if(isset($_POST['username'])) | |
{ | |
if(check_csrf()) | |
{ | |
echo 'Put form logic here'; | |
} | |
else | |
{ | |
echo 'Direct Post is not allowed. Use the form to submit your data.'; | |
} | |
} | |
?> | |
<form method="POST"> | |
<?php echo create_csrf_field(); ?> | |
<input type="text" name="username" value=""><br> | |
<input type="submit" value="Login"> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment