添加全新max-age属性

始于PHP 5.5,当 Set-Cookie 头被创建时,setcookie()setrawcookie() 函数将连同 Expires 发送 Max-Age 属性。这就是为何在Symfony 3.3中,cookies 将要包含 max-age 属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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",
// 假设当前时间是 "Wed, 28-Dec-2016 15:00:00 +0100",
// this will be the HTTP header added for the cookie:
// 这将是添加给cookie的HTTP头
 
// Symfony 3.2 and earlier / Symfony 3.2 和之前 :
// Set-Cookie: foo=bar; expires=Wed, 28-Dec-2016 15:10:00 +0100
 
// Symfony 3.3 and later / Symfony 3.3 和以后:
// Set-Cookie: foo=bar; Expires=Wed, 28-Dec-2016 15:10:00 +0100; Max-Age=600

使用字符串创建cookies

在Symfony 3.3中,cookies可以使用字符串来创建,这利益于全新的 Cookie::fromString 命名构造器:

1
2
3
4
5
6
7
use Symfony\Component\HttpFoundation\Cookie;
 
// Creating cookies with arguments / 创建带参cookie
$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 = Cookie::fromString('foo=bar; expires=Wed, 28-Dec-2016 15:00:00 +0100; path=/; domain=.example.com; secure; httponly');

你也可以用字符串添加cookie到响应头:

1
2
3
4
5
6
7
use Symfony\Component\HttpFoundation\Cookie;
 
// adding cookies using objects / 使用对象添加cookie
$response->headers->setCookie(new Cookie('foo', 'bar'));
 
// adding cookies using strings / 使用字符串添加cookie
$response->headers->set('set-cookie', 'foo=bar', false);