简体   繁体   English

从php读取JavaScript cookie

[英]Read a javascript cookie from php

I have a task which is compare up to five products from the product list. 我的任务是比较产品列表中的五个产品。 For that I have followed following steps: 为此,我遵循以下步骤:

step 1: 第1步:

set onclick event when we click add to compare button of each product. 当我们单击添加以比较每个产品的按钮时,设置onclick事件。 In this event I have set cookie by javascript using this code. 在这种情况下,我已使用此代码通过javascript设置了cookie。

// cookie is set by array because of we have to store 1 to 5 products
var comparearray  = [productid];
document.cookie = "compareitem" + "=" + comparearray;

It is successfully set the cookie value which holds product id of those are selected to compare. 成功设置了cookie值,该cookie值包含选择要比较的产品ID。

Step 2: In my PHP file I have tried to retrieve this cookie value.BY, 第2步:在我的PHP文件中,我尝试检索此Cookie值。

$cookie_val = $_COOKIE['compareitem '];

But it is not worked. 但这是行不通的。 I don't know this kind of concept is worth. 我不知道这种概念是否值得。 If know, give me the instructions how to solve my problem. 如果知道,请给我说明如何解决我的问题。 Thanks in advance. 提前致谢。

Since some people are writing that you can't use cookies set with JS in PHP, I'm going to answer that question now. 由于有人在写您不能在PHP中使用通过JS设置的cookie,因此我现在将回答这个问题。

Please try to use a cookieSet and cookieGet function, you can use the one from this answer: How do I create and read a value from cookie? 请尝试使用cookieSet和cookieGet函数,您可以使用以下答案中的一个: 如何创建和读取cookie中的值?

var createCookie = function(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

Note the last parameter which is written into the cookie.. the path-param is set to '/', so the root location! 请注意写入cookie的最后一个参数。path-param设置为'/',因此是根位置! Use a php script in the root location, so that both use the root location and not some other location. 在根目录位置使用php脚本,以便两者都使用根目录位置,而不使用其他位置。

Next please try to stringify the array with JSON. 接下来,请尝试使用JSON对数组进行字符串化。

var cookiedata = JSON.stringify(comparearray);

Then you should be able to get the cookie with PHP and parse the JSON to get the array back. 然后,您应该能够使用PHP获取cookie并解析JSON以返回数组。

Since it may be problem with path I suggest to set/get cookie with extended way: 由于路径可能存在问题,因此我建议使用扩展方式设置/获取Cookie:

document.cookie="foo=bar; path=/;"

or you can use this function: 或者您可以使用以下功能:

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM