如何在 cakephp 中 1 分钟后销毁 cookie?

how to destroy cookie after 1 minute in cakephp?

我是 cakephp 3.0 的新手。我已经成功创建了一个 cookie,但我想在一分钟后销毁该 cookie。到目前为止我已经做了:-

public function register_cookie(){
    $data = "Hello world!";
    $this->Cookie->write('dataFetch', $data, true, time() + (60 * 1));
}
public function getcookie() {
        $cookiedata = $this->Cookie->read('dataFetch');
        echo $cookiedata;
}

但是当我在 getCookie 函数一分钟后出现时,它仍然打印,即 "Hello World" 我想在一分钟后 cookie 过期。 提前致谢:)

首先,您应该检查cookie 过期日期是否设置正确。例如,在 Chrome 中(inspect element 触发控制台栏后),转到 Application\Storage\Cookies\Localhost 并检查 cookie。

在 cakephp 中,您可以使用

删除 cookie
$this->Cookie->delete('bar');

您也可以通过使用 time()-1

将过期日期设置为过去来销毁 cookie

在 cakephp 3.x 中,如文档所述,您可以拥有这些参数

CookieComponent::write(mixed $key, mixed $value = null)

但在 cakephp 中 2.x 它使用这些参数

CookieComponent::write(mixed $key, mixed $value = null, boolean $encrypt = true, mixed $expires = null)

要设置到期时间,你必须像这样设置配置

$this->Cookie->config([
    'expires' => '+10 days',
]);

所以你的代码会像这样

public function register_cookie(){
    $this->Cookie->config([
        'expires' => '+1 minute',
    ]);
    $this->Cookie->configKey('dataFetch', 'encryption', false);
    $data = "Hello world!";
    $this->Cookie->write('dataFetch', $data);
}