Created
July 22, 2012 00:00
Revisions
-
guisehn revised this gist
Jul 22, 2012 . No changes.There are no files selected for viewing
-
guisehn created this gist
Jul 22, 2012 .There are no files selected for viewing
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 charactersOriginal 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 '" />'; } } 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 charactersOriginal 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 }