Yii Error 400 The CSRF token could not be verified

2019-03-24 16:27发布

When I was trying to delete a post I got this error:

Yii Error 400 The CSRF token could not be verified

I don't know what is exactly causing this and to what it could be related. here is my action delete:

    public function actionDelete($id) {

         if (Yii::app()->request->isPostRequest) {
                // we only allow deletion via POST request
                $this->loadModel($id)->delete();

                // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
                if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
              throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    protected function afterDelete()
    {
        parent::afterDelete();
        Image::model()->deleteAll('name='.$this->id);
        Date::model()->deleteAll('tbl_show_id='.$this->id);
        Press::model()->deleteAll('tbl_show_id='.$this->id);
    }

标签: php yii
4条回答
Lonely孤独者°
2楼-- · 2019-03-24 17:04

I had the same issue but the following solved it. Hope it helps. I added

'params'=> array('YII_CSRF_TOKEN' => Yii::app()->request->csrfToken)

to the following code:

<?php
    echo CHtml::linkButton('Delete',array(
        'submit'=>$this->createUrl('delete',array('id'=>$model->id)),
        'confirm'=>"Are you sure want to delete ".$item->product->name."from the shopping cart?",
        'params'=> array('YII_CSRF_TOKEN' => Yii::app()->request->csrfToken)));
?>

Thanks.

查看更多
贪生不怕死
3楼-- · 2019-03-24 17:06

CSRF will keep giving you this error because you're deleting by using a URL (GET)

In order to use CSRF validation, you should make your request using a valid form that generates the CSRF token and submits it with every post.

Lookup: Yii CForm

查看更多
ら.Afraid
4楼-- · 2019-03-24 17:07

Even if you followed the Yii CSRF documentation correctly your error could be caused by a caching system. In my case the server cached the login page and then served the same token over and over again with the login form thus returning false on verification.

查看更多
ら.Afraid
5楼-- · 2019-03-24 17:16

It seems you've enabled CSRF validation. If you want to use it, read the doc and make sure you send the CSRF token in every POST request.

查看更多
登录 后发表回答