【问题标题】:Prestashop cookie is being cached to old value - Could it be a CDN issue?Prestashop cookie 被缓存为旧值 - 这可能是 CDN 问题吗?
【发布时间】:2019-11-21 04:43:30
【问题描述】:

在我的任务中,我需要创建一个在用户会话中持续存在的布尔变量,所以我想到了一个 cookie(我使用的是 Prestashop,所以应该是 $this->context->cookie->myVariable)。

用户会选中页面中的复选框,这将触发 AJAX 请求到更改相关 cookie 值的脚本。在 AJAX 请求成功后,我预计网页的进一步请求/重新加载会根据 cookie 的值呈现略有不同。

我的方法在 localhost 上运行良好,但在我们的生产网站(包括 Cloudflare CDN)上,它一直显示 cookie 变量的旧值。这可能是缓存旧 cookie 值的 CDN 吗?还是我在这里做错了什么?

下面是设置变量的 PHP 脚本:

<?php

include_once('./config/config.inc.php');
include_once('./config/settings.inc.php');
include_once('./classes/Cookie.php');

$context = Context::getContext();

//switching the value of myVariable
if(!$context->cookie->myVariable) {
    $context->cookie->__set('myVariable', true);
}

else {
    $context->cookie->__set('myVariable', false);
}

die("Success!");

以及ajax请求的Javascript代码:

$.post("url/of/script", null, function(res) { 
    if(res.includes("Success")) {
        //do something on success
        //I expect this request to have changed the cookie's value, so that on further requests I would get the right results displayed. It is not the case on production site only.
    }
 });

【问题讨论】:

    标签: php ajax cookies prestashop prestashop-1.7


    【解决方案1】:

    经过进一步研究,我遇到了this answer,它救了我的命!

    我确实知道Cache-control 标头,并在发布此问题之前尝试使用它,但它不起作用。原来我需要把它放在之前设置cookie,而不是之后! Location 标头也是如此,由于我想要实现的功能,我目前还添加了它。

    底线:如果您想使用 Cache-controlLocation 标头,请在更改 cookie 之前指定它们,而不是之后!

    我更新的 PHP 代码:

    <?php
    
    include_once('./config/config.inc.php');
    include_once('./config/settings.inc.php');
    include_once('./classes/Cookie.php');
    
    //the mighty headers!!
    header("Location: $redirect_url"); //redirect - a functionality I need now
    header('Cache-control: no-store, no-cache, must-revalidate'); //cache control header
    
    
    $context = Context::getContext();
    
    if(!$context->cookie->made_in_lb) {
        $context->cookie->__set('myVariable', true);
    }
    
    else {
        $context->cookie->__set('myVariable', false);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-21
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多