Last active
June 2, 2023 23:08
-
-
Save ziadoz/3454607 to your computer and use it in GitHub Desktop.
Simple PHP / jQuery CSRF Protection
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 | |
// See: http://blog.ircmaxell.com/2013/02/preventing-csrf-attacks.html | |
// Start a session (which should use cookies over HTTP only). | |
session_start(); | |
// Create a new CSRF token. | |
if (! isset($_SESSION['csrf_token'])) { | |
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32)); | |
} | |
// Check a POST is valid. | |
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) { | |
// POST data is valid. | |
} | |
?> | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
<title>PHP CSRF Protection</title> | |
<script> | |
window.csrf = { csrf_token: '<?php echo $_SESSION['csrf_token']; ?>' }; | |
$.ajaxSetup({ | |
data: window.csrf | |
}); | |
$(document).ready(function() { | |
// CSRF token is now automatically merged in AJAX request data. | |
$.post('/awesome/ajax/url', { foo: 'bar' }, function(data) { | |
console.log(data); | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<form action="index.php" method="post" accept-charset="utf-8"> | |
<input type="text" name="foo" /> | |
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" /> | |
<input type="submit" value="Submit" /> | |
</form> | |
</body> | |
</html> |
You shouldn't be using this code (or any code you've just plucked off Gists for that matter). It's seven years old and has many issues (e.g. no session id regeneration, no timing safe comparison, doesn't clear tokens when used).
I recommend taking a look at this guide a starting point instead: https://paragonie.com/blog/2017/12/2018-guide-building-secure-php-software
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think there's a way: