yii2 Setting a cookie


Example

To set a cookie i.e. to create it and schedule for sending to the browser you need to create new \yii\web\Cookie class instance and add it to response cookies collection:

$cookie = new Cookie([
    'name' => 'cookie_monster',
    'value' => 'Me want cookie!',
    'expire' => time() + 86400 * 365,
]);
\Yii::$app->getResponse()->getCookies()->add($cookie);

In the above we're passing parameters to cookie class constructor. These basically the same as used with native PHP setcookie function:

  • name - name of the cookie.
  • value - value of the cookie. Make sure it's a string. Browsers typically aren't happy about binary data in cookies.
  • domain - domain you're setting the cookie for.
  • expire - unix timestamp indicating time when the cookie should be automatically deleted.
  • path - the path on the server in which the cookie will be available on.
  • secure - if true, cookie will be set only if HTTPS is used.
  • httpOnly - if true, cookie will not be available via JavaScript.