Contributed by
Roland Franssen
in #20569
and #20644.
Add the new max-age
attribute¶
Starting with PHP 5.5, the setcookie()
and setrawcookie()
functions send
the Max-Age
attribute alongside Expires
when a Set-Cookie
header is
created. That's why in Symfony 3.3, cookies will start including the max-age
attribute:
1 2 3 4 5 6 7 8 9 10 11 12 13 | useSymfony\Component\HttpFoundation\Cookie;$cookie=newCookie('foo','bar',strtotime('now + 10 minutes'));// $cookie->getMaxAge() = 600// Assuming that the current time is "Wed, 28-Dec-2016 15:00:00 +0100",// this will be the HTTP header added for the cookie:// Symfony 3.2 and earlier:// Set-Cookie: foo=bar; expires=Wed, 28-Dec-2016 15:10:00 +0100// Symfony 3.3 and later:// Set-Cookie: foo=bar; Expires=Wed, 28-Dec-2016 15:10:00 +0100; Max-Age=600 |
Creating cookies with strings¶
In Symfony 3.3, cookies can be created using strings thanks to the newCookie::fromString()
named constructor:
1 2 3 4 5 6 7 | useSymfony\Component\HttpFoundation\Cookie;// Creating cookies with arguments$cookie=newCookie('foo','bar',strtotime('Wed, 28-Dec-2016 15:00:00 +0100'),'/','.example.com',true,true,true),// Creating cookies with a string$cookie=Cookie::fromString('foo=bar; expires=Wed, 28-Dec-2016 15:00:00 +0100; path=/; domain=.example.com; secure; httponly'); |
You can also use strings to add cookies to the response headers:
1 2 3 4 5 6 7 | useSymfony\Component\HttpFoundation\Cookie;// adding cookies using objects$response->headers->setCookie(newCookie('foo','bar'));// adding cookies using strings$response->headers->set('set-cookie','foo=bar',false); |