Skip to content

Instantly share code, notes, and snippets.

@guisehn
Created July 22, 2012 00:00

Revisions

  1. guisehn revised this gist Jul 22, 2012. No changes.
  2. guisehn created this gist Jul 22, 2012.
    39 changes: 39 additions & 0 deletions csrf.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    <?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 '" />';
    }
    }
    19 changes: 19 additions & 0 deletions usage.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    <?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
    }