Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php csrf protection library

Tags:

php

csrf

Are there any libraries to protect against CSRF(PHP5.1/5.2) or do I need to create on myself? I use this snippet from Chris, but without a library I am getting a lot of duplication on every page.

I found this library for PHP5.3, but I am wondering if there are any on PHP5.1/5.2 because I don't believe yet all hosting support PHP5.3.

like image 327
Alfred Avatar asked May 21 '26 12:05

Alfred


1 Answers

Since I use Kohana - I've just extended couple of its core classes. It can be used in any code with a little changes though:

class Form extends Kohana_Form
{
  public static function open($action = NULL, array $attributes = null)
  {
      if (is_null($action))
      {
          $action = Request::current()->uri . ($_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '');
      }

    $open = parent::open($action, $attributes);
    $open .= parent::hidden(self::csrf_token_field(), self::csrf_token());
    return $open;
  }

  public static function csrf_token_field()
  {
    return 'csrf_token';
  }

  public static function csrf_token()
  {
    $session = Session::instance();
    $token = $session->get(self::csrf_token_field());

    if (!$token)
    {
      $session->set(self::csrf_token_field(), $token = md5(uniqid()));
    }

    return $token;
  }
}

class Validate extends Kohana_Validate
{
    public function __construct(array $array, $csrf = true)
    {
        parent::__construct($array);
        if ($csrf)
            $this->add_csrf();
    }

    public static function factory(array $array, $csrf = true)
    {
        return new Validate($array, $csrf);
    }

    private function add_csrf()
    {
        $this->rules(form::csrf_token_field(), array(
            'not_empty' => array(),
            'csrf' => array()
        ));
    }

    protected function csrf($token)
    {
        return $token == form::csrf_token();
    }

}
like image 110
zerkms Avatar answered May 23 '26 01:05

zerkms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!