Skip to content

Instantly share code, notes, and snippets.

@guisehn
Created July 22, 2012 00:00
Show Gist options
  • Save guisehn/3157627 to your computer and use it in GitHub Desktop.
Save guisehn/3157627 to your computer and use it in GitHub Desktop.
Simple class for CSRF protection
<?php
abstract class CSRF
{
const SESSION_NAME = 'nomedosite_csrf_token';
const FIELD_NAME = 'nomedosite_csrf_check';
private static function set_session()
{
if (!isset($_SESSION[self::SESSION_NAME]))
{
$_SESSION[self::SESSION_NAME] = uniqid(rand(1000, 9999), true);
}
}
public static function check()
{
self::set_session();
if (!isset($_POST[self::FIELD_NAME]) || $_POST[self::FIELD_NAME] != $_SESSION[self::SESSION_NAME])
{
header('HTTP/1.1 403 Forbidden');
exit('<h1>Forbidden</h1>');
}
}
public static function token($input = true)
{
self::set_session();
if ($input)
echo '<input type="hidden" name="' . self::FIELD_NAME . '" value="';
echo $_SESSION[self::SESSION_NAME];
if ($input)
echo '" />';
}
}
<?php
session_start();
require 'csrf.php';
if (isset($_POST['name']))
{
CSRF::check();
echo 'Hello ' . $_POST['name'];
}
else
{
?>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<label>Name: <input type="text" name="name" /></label>
<? CSRF::token() ?>
<button type="submit">Submit</button>
</form>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment