Sunday, June 17, 2012

Fixing The CSRF token could not be verified

"The CSRF token could not be verified", if you get this message while using YII Framework. the issue can happen in
1.You are not using CHtml Form widget
2.You are not using CActiveFormWidget
3.You are using cusom ajax handlers

If you are using CHtml Form widget or CActiveForm widget the Yii Framework automatically validate CSRF token, if we using custom form or custom jquery ajax methods we should pass YII_CSRF_TOKEN to POST request, this may solve the above issue


$csrfToken = Yii::app()->request->csrfToken; // 
will return the csrf token associated with the context, you can now use that csr token to pass in jquery ajax functions


to check csrfvalidation enabled in application use the following method to get status
if(Yii::app()->request->enableCsrfValidation) 

Getting CSRF Token from javascript
YII_CSRF_TOKEN=$('input[name="YII_CSRF_TOKEN"]').val();

1 comment:

Lokashree sam said...

It was a great information and Its really worth reading it. The author did an mind blowing work by describing each and every concept in detail. Thanks for such an informative post. Please keep up your good work.
Engineering Colleges In Chennai, Nautical Science Colleges In Chennai