Php csrf protection library

Are there any libraries for protection 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 get a lot of duplicates on every page.

I found this library for PHP5.3, but I'm wondering if there is any on PHP5.1 / 5.2, because I do not believe that all hosting supports PHP5.3.

+3
source share
1 answer

Since I use Kohana - I just expanded a couple of my main classes. It can be used in any code with minor changes:

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();
    }

}
+2
source

Source: https://habr.com/ru/post/1787597/


All Articles