2011-01-25 87 views
3

是否有任何庫可以防止CSRF(PHP5.1/5.2)或我需要自己創建?我使用Chris這個片段,但沒有一個庫,我在每一頁上都有很多重複。php csrf保護庫

我發現這個library爲PHP5.3,但我想知道是否有任何PHP5.1/5.2,因爲我不相信所有託管支持PHP5.3。

+1

它很容易自己寫。 – zerkms 2011-01-25 01:48:44

回答

2

由於我使用Kohana - 我只是擴展了它的幾個核心類。它可以在任何代碼中使用,但有一點變化:

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

}