Skip to content

Instantly share code, notes, and snippets.

@FSX
Created January 14, 2011 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FSX/779565 to your computer and use it in GitHub Desktop.
Save FSX/779565 to your computer and use it in GitHub Desktop.
A simple anti-XSRF class.
<?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