0

首先,我已经尝试了这两个链接中提供的这两种解决方案

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

如何在 CakePHP 3.5 的控制器级别创建 cookie?

但是,它只是不工作。我提供了一个示例,说明我如何尝试编写和读取 cookie。但它们都不起作用。

写饼干

use Cake\Http\Cookie\CookieCollection;
use Cake\Http\Cookie\Cookie;

public function writeCookie() {
        $cookie = new Cookie(
            'remember_me', // name
            1, // value
            (Time::now())->modify('+1 year'), // expiration time, if applicable
            '/', // path, if applicable
            '', // domain, if applicable
            false, // secure only?
            true // http only ?
        );
        $cookies = new CookieCollection([$cookie]);//To create new collection
        $cookies = $cookies->add($cookie);//to add in existing collection

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

阅读饼干

public function readCookie(){
       $cookie = $this->request->getCookie('remember_me');
       debug($cookie); //is getting a null value
}

有人能指出我在 CakePHP 3.5 中写入和读取 cookie 的正确方向吗?

4

1 回答 1

0

问题是您以错误的方式编写cookie。您应该在添加到 Cookie 集合后编写 $cookie。检查下面的代码。

写饼干

    $cookie = new Cookie('remember_me', 
        1, 
        (Time::now())->modify('+1 year'),
        '/', // path, if applicable
        '', // domain, if applicable
        false, // secure only?
        true // http only ?
    );
    $cookies = new CookieCollection([$cookie]);
    $this->response = $this->response->withCookie($cookie);
于 2018-09-18T14:47:43.587 回答