如何在 Cakephp 3.5 中设置和获取 Cookie

How to set and get Cookies in Cakephp 3.5

我已阅读 Cakephp 文档,但它运行不佳。 这是我的代码,

$this->response = $this->response->withCookie('remember_me', [
    'value' => 'yes',
    'path' => '/',
    'httpOnly' => true,
    'secure' => false,
    'expire' => strtotime('+1 year')
]);
$rememberMe = $this->request->getCookie('remember_me');

请查看文档。您将在以下 link:

中找到它

https://book.cakephp.org/3.0/en/controllers/request-response.html#Cake\Http\Cookie\CookieCollection

创建 cookie

use Cake\Http\Cookie\Cookie;

$cookie = new Cookie(
    'remember_me', // name
    1, // value
    new DateTime('+1 year'), // expiration time, if applicable
    '/', // path, if applicable
    'example.com', // domain, if applicable
    false, // secure only?
    true // http only ? );

现在将 cookie 添加到 cookie 集合中:

use Cake\Http\Cookie\CookieCollection;
$cookies = new CookieCollection([$cookie]);//To create new collection
$cookies = $cookies->add($cookie);//to add in existing collection

现在这样读取cookie。

   $cookie = $cookies->get('remember_me');

希望您会发现它有效。

这里要提一个重点:Cookie的写入和读取必须是两个独立的http请求。