0

我正在设置一个网页,使用 cookie 来确定用户是否已经登录,使用包含他的 id 的 cookie。问题是:cookie 未写入或 cookie 集合未更新。

我试过阅读文档,但它没有定义 CookieCollection 的用法。

这是我编写 cookie 的函数:

function displayData(){
        $id = $this->getRequest()->getSession()->read('id');
        $cookies = CookieCollection::createFromServerRequest($this->getRequest());
        if(!$cookies->has('id')){
            $cookie = (new Cookie('id'))
                ->withValue($id)
                ->withExpiry(new DateTime('+999 year'))
                ->withPath('/')
                ->withDomain('break-first.eu')
                ->withSecure(true)
                ->withHttpOnly(true);
            $cookies = $cookies->add($cookie);
        }
        // Other stuff
    }

在我尝试阅读的地方:

function index(){
        $cookies = $this->getRequest()->getCookieCollection();
        dd($cookies);
    }

我希望有一个名为“id”的 cookie,但我没有。只有 CAKEPHP 和 pll_language 出现。

4

1 回答 1

1

首先,CakePHP 通过 cookie 身份验证提供身份验证功能,您可能想看看它而不是驱动自定义解决方案。

话虽这么说,您在那里所做的将创建一个 cookie 集合对象,但这只是空间中某个地方的一个单独对象,它不会影响您的应用程序的状态,为了实现这一点,您必须实际修改响应对象。

但是,您在那里尝试做的事情首先不需要 cookie 集合,您可以通过请求和响应对象提供的方法直接读取和写入 cookie,例如:

// will be `null` in case the cookie doesn't exist
$cookie = $this->getRequest()->getCookie('id');
// responses are immutable, they need to be reassinged
this->setResponse(
    $this->getResponse()->withCookie(
        (new Cookie('id'))
            ->withValue($id)
            ->withExpiry(new DateTime('+999 year'))
            ->withPath('/')
            ->withDomain('break-first.eu')
            ->withSecure(true)
            ->withHttpOnly(true)
    )
);

如果您出于某种原因在哪里使用 cookie 集合,那么您可以将withCookieCollection()其传递到响应中:

$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;
    }
}

webroot/index.php您可以将其作为调用的第二个参数传递到文件中的应用程序中$server->run()

// ...
$server->emit($server->run(null, new \App\Http\Response()));

也可以看看

于 2019-06-26T14:40:17.580 回答