yii2-request

The web Request class represents an HTTP request

It encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers.

Also it provides an interface to retrieve request parameters from $_POST, $_GET, $_COOKIES and REST parameters sent via other HTTP methods like PUT or DELETE.

HTTP Headers

// $headers is an object of yii\web\HeaderCollection
$headers = Yii::$app->request->headers;

$accept = $headers->get('Accept');

if( $headers->has('User-Agent') ) { /* there is User-Agent header */ }

Client Information

获取用户 IP:

$userHost = Yii::$app->request->userHost;
$ip = Yii::$app->getRequest()->getUserIP();

CSRF

yii\web\User

/**
 * Regenerates CSRF token
 *
 * @since 2.0.14.2
 */
protected function regenerateCsrfToken()
{
    $request = Yii::$app->getRequest();
    if ($request->enableCsrfCookie || $this->enableSession) {
        $request->getCsrfToken(true);
    }
}

在配置文件中设置 csrf 令牌名称:

'components' => [
    'request' => [
        'csrfParam' => '_csrf',
    ],
    // ..
]

在 post 请求中必须带上该参数,否则返回 400 无法校验请求:

Bad Request (#400)
Unable to verify your data submission. 

Adding CSRF protection:

<form method="POST">
    <input id="form-token" type="hidden" name="<?=Yii::$app->request->csrfParam?>"
           value="<?=Yii::$app->request->csrfToken?>"/>
    <input type="submit" value="ok!">
</form>