Created
January 14, 2011 12:49
-
-
Save FSX/779565 to your computer and use it in GitHub Desktop.
A simple anti-XSRF class.
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 | |
/** | |
* A simple anti-XSRF class. | |
*/ | |
class xsrf | |
{ | |
static private $_token = false; | |
/** | |
* Generate an XSRF token. | |
* | |
* Generate an XSRF token and store it in a cookie, but first check if the | |
* cookie already exists or if the token is already generated. Then return it. | |
* See: http://en.wikipedia.org/wiki/Cross-site_request_forgery | |
* | |
* @return string | |
*/ | |
static function token() | |
{ | |
if (($token = get_cookie('xsrf')) !== false) | |
self::$_token =& $token; | |
elseif (!self::$_token) | |
{ | |
self::$_token = generate_hash(generate_salt()); | |
set_cookie('xsrf', self::$_token); | |
} | |
return self::$_token; | |
} | |
/** | |
* Compare XSRF token with $token. | |
* | |
* @param string $token | |
* @return boolean | |
*/ | |
static function check_cookie($token) | |
{ | |
if (!self::$_token) | |
self::token(); | |
return $token == self::$_token; | |
} | |
/** | |
* Return a hidden form field with the XSRF token. | |
* | |
* @return string | |
*/ | |
static function form_html() | |
{ | |
if (!self::$_token) | |
self::token(); | |
return '<input type="hidden" name="xsrf_token" value="'.self::$_token.'" />'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment