yii2关于HTTP请求处理的总结

本文详细解释了VerbFilter的作用与配置方法,并通过实例展示了如何限制或允许特定动作的HTTP请求方式,同时介绍了如何在请求处理中区分GET与POST请求,并演示了如何在Web应用中实现CSRF防范策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、VerbFilter

VerbFilter 是针对 HTTP 请求方式的过滤器,作用是定义访问指定动作所允许的HTTP请求,若不允许的HTTP请求到来,则会抛出一个 HTTP 405 错误。若不指定允许的请求方式,则默认允许当所有类型的请求方式 。

接下来,试一试 VerbFilter 的简单使用。

首先,在 SiteController 中添加代码
 

public function actionInfo()
    {
        return \Yii::createObject([
            'class' => 'yii\web\Response',
            'format' => \yii\web\Response::FORMAT_JSON,
            'data' => [
                'message' => 'hello world',
                'code' => 100,
            ],
        ]);
    }
上述代码,返回一个利用 FORMAT_JSON 格式化的字符串
使用URL:http://localhost/basic/web/index.php?r=site/info 访问的时候,成功返回

{"message":"hello world","code":100}

接着,在 behaviors() 中添加代码
public function behaviors()
    {
        return [
            ... ...
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],                   
                    'info' => ['post'],
                ],
            ],
        ];
    }
上述代码,在 behaviors() 中使用了过滤器 VerbFilter ,指明访问动作 info 时,只能使用 POST 请求方式
此时,使用RESTClient工具,选择 GET 请求方式进行访问的时候,返回 405 错误

再次修改代码,

public function behaviors()
    {
        return [
            ... ...
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],                   
                    'info' => ['post','get'],
                ],
            ],
        ];
    }
允许POST和GET两种请求方式访问动作Info,使用RESTClient工具访问,选择 GET 请求方式进行访问的时候获取到返回值

{"message":"hello world","code":100}

此时使用工具 RESTClient ,通过 post 发送请求,返回 405 错误。

这时候,修改 web.php 文件,

'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => '4mWc84oNsYJpc-nnnjMwyOOiCTgcThig',
            'enableCookieValidation' => false,
            'enableCsrfValidation' => false,
        ],
添加上这两行代码,警用cookie保护与CSRF防范策略
 'enableCookieValidation' => false,
 'enableCsrfValidation' => false,
再次通过 post 发送请求访问,成功。
注:CSRF验证
因为Web网页访问的时候,form表单中会有对应的一个隐藏input:_csrf进行验证,验证通过才可以正常进行访问;
而非网页访问方式(不通过Web表单,例如用命令行CURL请求)是无法通过csrf验证的。

2、HTTP 请求处理

在 SiteController 中添加代码

public function actionApitest(){
        $request = Yii::$app->request;
      
        if ($request->isGet)  {
            echo "the request method is GET" . "\n";

            echo "-------\$request->get('id')---------\n";
            $id = $request->get('id');
            // equivalent to: $id = isset($_GET['id']) ? $_GET['id'] : null;
            echo $id . "\n";
            echo "-------\$request->get('id','null')---------\n";
            $id = $request->get('id','null');
            // equivalent to: $id = isset($_GET['id']) ? $_GET['id'] : 1;
            echo $id . "\n";
        }
        if ($request->isPost)  {
            echo "the request method is POST" . "\n";

            echo "-------\$_POST------------------\n";
            echo var_dump($_POST) . "\n";
            echo "-------php://input-------------\n";
            $content = file_get_contents('php://input');
            echo $content . "\n";
            //echo json_encode($content). "\n";
            echo "-------request->post('message', 'other')---------\n";
            $message = $request->post('message', 'null');
            echo $message ;
        }
    }
用GET方式请求 URL:http://localhost/basic/web/index.php?r=site/apitest&id=1,返回

the request method is GET
-------$request->get('id')---------
1
-------$request->get('id','null')---------
1

用GET方式请求 URL:http://localhost/basic/web/index.php?r=site/apitest,返回

the request method is GET
-------$request->get('id')---------

-------$request->get('id','null')---------
null

用POST方式请求 URL:http://localhost/basic/web/index.php?r=site/apitest,Body填充值:

    {
        "message": "hello world",
        "code": 100
    }

返回结果为:

the request method is POST
-------$_POST------------------
array(0) {
}

-------php://input-------------
    {
        "message": "hello world",
        "code": 100
    }


-------request->post('message', 'other')---------
null



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值