Skip to content

Instantly share code, notes, and snippets.

@huglester
Forked from dhrrgn/csrf.php
Created October 23, 2011 07:10
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 huglester/1306978 to your computer and use it in GitHub Desktop.
Save huglester/1306978 to your computer and use it in GitHub Desktop.
Simple, yet effective CSRF class for FuelPHP.
<?php
/**
* Simple, yet effective CSRF class for FuelPHP.
*
* @author Dan Horrigan
* @license MIT License
* @copyright 2011 Dan Horrigan
*/
/**
* Csrf class helps you protect against Csrf attacks.
*/
class Csrf
{
/**
* @var string The key to use for storing the token in the session/input/meta tag
*/
protected static $token_key = 'csrf-token';
/**
* @var int Length of the CSRF token
*/
protected static $token_length = 42;
/**
* @var string CSRF Token
*/
protected static $token = null;
/**
* Gets the current CSRF token. It will generate a new one if one
* does not already exist, it will then set it in the Session.
*
* @return string
*/
public static function token()
{
if (static::$token === null)
{
$unique_id = Str::random('alnum', 20);
static::$token = $unique_id.':'.Str::random('alnum', static::$token_length);
Session::set($unique_id.'-'.static::$token_key, static::$token);
}
return static::$token;
}
/**
* Validates either the fiven CSRF token or from the 'csrf-token' POST field.
*
* @param string|null Token to check or null to default to POST
* @return bool
*/
public static function validate($user_token = null)
{
if ($user_token === null)
{
$user_token = Input::post(static::$token_key, null);
}
$user_token = trim(str_replace("\0", '', $user_token));
list($unique_id, $token) = explode(':', $user_token);
$valid = true;
if ($user_token !== Session::get($unique_id.'-'.static::$token_key))
{
$valid = false;
}
return $valid;
}
/**
* Generates a meta tag with the generated csrf-token. This is useful for
* protecting AJAX calls.
*
* @return string
*/
public static function meta_tag()
{
$token = static::token();
return html_tag('meta', array('name' => static::$token_key, 'content' => $token));
}
/**
* Generates a hidden input with the generated csrf-token.
*
* @return string
*/
public static function input()
{
$token = static::token();
return html_tag('input', array(
'type' => 'hidden',
'name' => static::$token_key,
'id' => static::$token_key,
'value' => $token
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment