Skip to content

Instantly share code, notes, and snippets.

@nmvuong92 nmvuong92/index.php forked from ziadoz/index.php
Created Jan 17, 2019

What would you like to do?
Simple PHP / jQuery CSRF Protection
// See:
// Start a session (which should use cookies over HTTP only).
// 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">
<meta charset="utf-8" />
<title>PHP CSRF Protection</title>
window.csrf = { csrf_token: '<?php echo $_SESSION['csrf_token']; ?>' };
data: window.csrf
$(document).ready(function() {
// CSRF token is now automatically merged in AJAX request data.
$.post('/awesome/ajax/url', { foo: 'bar' }, function(data) {
<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" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.