Cakephp 如何在多个函数中使用CookieCollection
我正在使用cookies设置网页,以确定用户是否已登录,并使用包含其id的cookie。问题是:cookie未写入或cookie集合未更新 我尝试阅读文档,但它没有定义CookieCollection的用法 下面是我编写cookie的函数:Cakephp 如何在多个函数中使用CookieCollection,cakephp,cookies,cakephp-3.7,Cakephp,Cookies,Cakephp 3.7,我正在使用cookies设置网页,以确定用户是否已登录,并使用包含其id的cookie。问题是:cookie未写入或cookie集合未更新 我尝试阅读文档,但它没有定义CookieCollection的用法 下面是我编写cookie的函数: 函数displayData(){ $id=$this->getRequest()->getSession()->read('id'); $cookies=CookieCollection::createFromServerRequest($this->get
函数displayData(){
$id=$this->getRequest()->getSession()->read('id');
$cookies=CookieCollection::createFromServerRequest($this->getRequest());
如果(!$cookies->has('id')){
$cookie=(新cookie('id'))
->withValue($id)
->到期日(新日期时间(“+999年”))
->withPath(“/”)
->withDomain('break-first.eu')
->带安全(真)
->仅限HttpOnly(true);
$cookies=$cookies->add($cookie);
}
//其他东西
}
在我尝试阅读的地方:
函数索引(){
$cookies=$this->getRequest()->getCookieCollection();
dd(饼干);
}
我希望有一块名为“id”的饼干,但我没有。只有CAKEPHP和pll_语言出现。首先,CAKEPHP通过cookie身份验证提供身份验证功能,您可能希望了解这一点,而不是驱动自定义解决方案
// will be `null` in case the cookie doesn't exist
$cookie = $this->getRequest()->getCookie('id');
如果出于任何原因需要在何处使用cookie集合,则应使用with CookieCollection()
将其传递到响应中:
$this->setResponse($this->getResponse()->withCookieCollection($cookies));
例如,如果遇到,可以使用重写的Response::convertCookieToArray()
方法创建一个自定义响应类,并将字符串转换为整数(确保PHP_INT_MAX
覆盖了您的目标日期时间戳,32位不兼容是CakePHP 4.x中的修复程序可能无法达到3.x的原因),类似于:
src/Http/Response.php
namespace App\Http;
use Cake\Http\Cookie\CookieInterface;
use Cake\Http\Response as CakeResponse;
class Response extends CakeResponse
{
protected function convertCookieToArray(CookieInterface $cookie)
{
$data = parent::convertCookieToArray($cookie);
$data['expire'] = (int)$data['expire'];
return $data;
}
}
您可以将其作为$server->run()
调用的第二个参数传递到webroot/index.php文件中的应用程序中:
// ...
$server->emit($server->run(null, new \App\Http\Response()));
另见
您好,谢谢您的回答。但是,它似乎不起作用,因为我现在有一个警告:“警告(2):setcookie()希望参数3是整数,字符串给定[CORE/src/Http/ResponseEmitter.php,第210行]”,这从何而来?(我使用的解决方案没有CookieCollection)编辑:稍后我将查看Auth,谢谢。@Baka,从7.3.0开始已修复/更改。您可以通过将到期日值作为整数传递来解决此问题(我已更新了示例)。CakePHP 4将日期对象转换为整数(),这可能不会出现在CakePHP 3.x中,因为32位系统上的大整数可能会出现问题。好的,谢谢你,当老板将php更新到7.3.0时,我会回来找你。@Baka我不会依赖接受字符串的行为,因为严格来说,根据函数的签名,即使在错误报告中接受浮点是不对的。如果你问我的话,使用整数是最好的选择。我一定会尝试一下,谢谢你的回复!
// ...
$server->emit($server->run(null, new \App\Http\Response()));