【问题标题】:how to destroy cookie after 1 minute in cakephp?如何在 cakephp 中 1 分钟后销毁 cookie?
【发布时间】:2017-06-28 19:06:01
【问题描述】:

我是 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 之前又写了一遍。
  • 我提供了这些我自己的名字
  • 您从哪里调用了register_cookiegetcookie 函数?

标签: php cakephp cookies cakephp-3.x


【解决方案1】:

在 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);
}

【讨论】:

  • 但是当我在一分钟之间读取 cookie 数据时,它不是在 getCookie 函数中打印数据
【解决方案2】:

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

在 cakephp 中,您可以使用

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

您还可以通过使用 time()-1 将过期日期设置为过去来销毁 cookie

【讨论】:

  • 如何在 getcookie 函数中做到这一点
  • 您的代码是正确的...如果它显示 2017-03-10 表示它将在 3 月 10 日到期。检查您的时钟设置是否正确。应该是您当前时间的 2 月 10 日 + 60 秒。
猜你喜欢
  • 1970-01-01
  • 2014-09-30
  • 1970-01-01
  • 1970-01-01
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
相关资源
最近更新 更多