简体   繁体   中英

Yii2 Allow action access only by POST request

I have created a yii2 controller, which meant to display statistics from database, for a specific user. There is a ajax request, performed to my controller action, but i want to restrict to allow only POST method for this action.

<?php
use yii\web\Response;
namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\StatsModel;

class DataController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
        [
            'class' => 'yii\filters\ContentNegotiator',
            'only' => ['stats'],
             'formats' => [
                'application/json' => Response::FORMAT_JSON 
              ],                
           ],
       ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionStats()
    {   
         //how can i restrict this action to only POST http method?
         return StatsModel::find()->all();
    }
}

I need to restrict actionStats() to HTTP Post method only.

Usually you'd allow post only adding something like this to your behaviors:

'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'stats' => ['POST'],
            ],
        ],

And if you are accessing this action only through ajax, in your action you could add the following check

if(Yii::$app->request->isAjax)
{
    //in case you want to return JSON formatted response
    Yii:$app->response->format = Response::FORMAT_JSON;
}

You can check this cookbook as well:

https://books.google.com.sv/books?id=CJrcDgAAQBAJ&pg=PA193&lpg=PA193&dq=yii2+isajax&source=bl&ots=lRFEiPbN3K&sig=MFGo7VostVkxNZDbXGemXrm-qA8&hl=es&sa=X&ved=0ahUKEwjE9ZXSh7nbAhWPk1kKHW3wCeEQ6AEIYTAF#v=onepage&q=yii2%20isajax&f=false

Finally, you can just make the check for post in your action like this

public function actionStats()
{   
     if(Yii::$app->request->isPost())
     {
         //your logic here
         return StatsModel::find()->all();
     }
     else
         //throw an exception or return false
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM