YII2 Summary of HTTP request handling

Source: Internet
Author: User

1. Verbfilter

Verbfilter is a filter for HTTP requests that defines the HTTP requests allowed for access to the specified action, and throws an HTTP 405 error if an HTTP request is not allowed to arrive. If you do not specify the allowed request mode, the default is to allow all types of requests.

Next, try verbfilter 's simple use.

First, add the code in the Sitecontroller

Public Function Actioninfo ()    {        return \yii::createobject ([            ' class ' = ' Yii\web\response ',            ' Format ' = = \yii\web\response::format_json,            ' data ' = [                ' message ' = ' Hello World ',                ' code ' = ]        );    
The code above returns an exploit FORMAT_JSONFormatted string
When using Url:http://localhost/basic/web/index.php?r=site/info access, the successful return

{"Message": "Hello World", "Code": 100}

Next, add the code in Behaviors ()
Public function behaviors ()    {        return [            ...]            Verbs ' = ' + ['                class ' + Verbfilter::classname (),                ' actions ' = [' logout ' = ' + ' ['                    post '],                                       ' Info ' = = [' Post '],], [],]        ;    }
The above code, the filter is used in the behaviors () Verbfilter, indicating that access to action info can only be done using the POST request mode
In this case, a 405 error is returned when you use the Restclient tool to select a GET request method for access


Modify the code again,

Public function behaviors ()    {        return [            ...]            Verbs ' = ' + ['                class ' + Verbfilter::classname (),                ' actions ' = [' logout ' = ' + ' ['                    post '],                                       ' Info ' = = [' Post ', ' get '],                ],]            ,        ];    }
Allows post and get two requests to access the action info, accessed using the Restclient tool, and gets the return value when Access is selected by the GET request

{"Message": "Hello World", "Code": 100}

At this point, using the tool restclient, send the request via post and return a 405 error.

At this time, modify the web.php file,

' Request ' = [            //!!! Insert a secret key in the following (if it's empty)-this is required by cookie validation            ' cookievalidationkey ' = ' 4mwc84onsyjpc-nnnjmwyooictgcthig ',            ' enablecookievalidation ' and false,            ' enablecsrfvalidation ' = False,        ],
Add these two lines of code, police cookie protection and CSRF prevention strategy
' Enablecookievalidation ' = False, ' enablecsrfvalidation ' = False,
Send the request again via post for access, success.
Note: CSRF Verification
Because Web pages are accessed, a form will have a corresponding hidden input:_csrfTo verify and verify that the access can be done normally;
Instead of Web page access (not through Web forms, such as a command-line curl request), the csrf验证Of

2. HTTP Request Processing

Add code to 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; }    }
Request Url:http://localhost/basic/web/index.php?r=site/apitest&id=1 in Get mode, return

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

Request Url:http://localhost/basic/web/index.php?r=site/apitest in Get mode, return

The request method is GET-------$request->get (' id ')----------------$request->get (' id ', ' null ')---------NULL

To request a url:http://localhost/basic/web/index.php?r=site/apitest,body fill value by post:

    {        "message": "Hello World",        "code":    
The returned result is:

The request method is POST-------$_post------------------Array (0) {}-------Php://input-------------    {        " Message ": Hello World",        "code": $    -------request->post (' message ', ' other ')---------null



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

YII2 Summary of HTTP request handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.