yii\web\Request::getHeaders PHP Method

getHeaders() public method

The header collection contains incoming HTTP headers.
public getHeaders ( ) : HeaderCollection
return HeaderCollection the header collection
    public function getHeaders()
    {
        if ($this->_headers === null) {
            $this->_headers = new HeaderCollection();
            if (function_exists('getallheaders')) {
                $headers = getallheaders();
            } elseif (function_exists('http_get_request_headers')) {
                $headers = http_get_request_headers();
            } else {
                foreach ($_SERVER as $name => $value) {
                    if (strncmp($name, 'HTTP_', 5) === 0) {
                        $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
                        $this->_headers->add($name, $value);
                    }
                }
                return $this->_headers;
            }
            foreach ($headers as $name => $value) {
                $this->_headers->add($name, $value);
            }
        }
        return $this->_headers;
    }

Usage Example

Example #1
0
 /**
  * Authenticates the current user.
  *
  * @param User     $user
  * @param Request  $request
  * @param Response $response
  *
  * @return IdentityInterface the authenticated user identity. If authentication information is not provided, null will be returned.
  * @throws UnauthorizedHttpException if authentication information is provided but is invalid.
  */
 public function authenticate($user, $request, $response)
 {
     $authHeader = $request->getHeaders()->get(Yii::$app->params['auth_header_name']);
     if ($authHeader !== null) {
         $user->on(User::EVENT_AFTER_LOGIN, function (UserEvent $event) {
             /** @var UserModel $user */
             $user = $event->identity;
             $user->regenerateToken();
             Yii::$app->getResponse()->getHeaders()->set(Yii::$app->params['auth_header_name'], $user->token);
         });
         /** @var UserModel $identity */
         $identity = $user->loginByAccessToken($authHeader, get_class($this));
         if ($identity === null) {
             $this->handleFailure($response);
         }
         return $identity;
     }
     return null;
 }