New in Symfony 3.3: Cookie improvements
December 28, 2016 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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
use Symfony\Component\HttpFoundation\Cookie;
$cookie = new Cookie('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 new
Cookie::fromString()
named constructor:
1 2 3 4 5 6 7
use Symfony\Component\HttpFoundation\Cookie;
// Creating cookies with arguments
$cookie = new Cookie('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
use Symfony\Component\HttpFoundation\Cookie;
// adding cookies using objects
$response->headers->setCookie(new Cookie('foo', 'bar'));
// adding cookies using strings
$response->headers->set('set-cookie', 'foo=bar', false);
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.