yii2 Cookies Cookies for subdomains

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Because of security reasons, by default cookies are accessible only on the same domain from which they were set. For example, if you have set a cookie on domain example.com, you cannot get it on domain www.example.com. So if you're planning to use subdomains (i.e. admin.example.com, profile.example.com), you need to set domain explicitly:

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

Now cookie can be read from all subdomains of example.com.



Got any yii2 Question?