是否可以阻止使用 Javascript 或 PHP 设置 cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10306254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:47:24  来源:igfitidea点击:

Is it possible to block cookies from being set using Javascript or PHP?

phpjavascriptcookiesblocking

提问by freestate

A lot of you are probably aware of the new EU privacy law, but for those who are not, it basically means no site operated by a company resident in the EU can set cookies classed as 'non-essential to the operation of the website' on a visitors machine unless given express permission to do so.

很多人可能都知道新的欧盟隐私法,但对于那些不知道的人来说,这基本上意味着居住在欧盟的公司运营的任何网站都不能设置归类为“对网站运营非必要”的 cookie在访客机器上,除非获得明确许可。

So, the question becomes how to best deal with this?

那么,问题就变成了如何最好地处理这个问题?

Browsers obviously have the ability to block cookies from a specific website built in to them. My question is, is there a way of doing something similar using JS or PHP?

浏览器显然能够阻止来自内置于它们的特定网站的 cookie。我的问题是,有没有办法使用 JS 或 PHP 做类似的事情?

i.e. intercept any cookies that might be trying to be set (including 3rd party cookies like Analytics, or Facebook), and block them unless the user has given consent.

即拦截任何可能试图设置的 cookie(包括 3rd 方 cookie,如 Analytics 或 Facebook),并在未经用户同意的情况下阻止它们。

It's obviously possible to delete all cookies once they have been set, but although this amounts to the same thing as not allowing them to be set in the first place, I'm guessing that it's not good enough in this case because it doesn't adhere to the letter of the law.

显然,一旦设置了所有 cookie,就可以删除它们,但是尽管这相当于一开始就不允许设置它们,但我猜在这种情况下它不够好,因为它没有遵守法律条文。

Ideas?

想法?

采纳答案by Michael

I'm pretty interested in this answer too. I've accomplished what I need to accomplish in PHP, but the JavaScript component still eludes me.

我也对这个答案很感兴趣。我已经完成了我需要在 PHP 中完成的工作,但是 JavaScript 组件仍然让我望而却步。

Here's how I'm doing it in PHP:

这是我在 PHP 中的做法:

$dirty = false;
foreach(headers_list() as $header) {
    if($dirty) continue; // I already know it needs to be cleaned
    if(preg_match('/Set-Cookie/',$header)) $dirty = true;
}
if($dirty) {
    $phpversion = explode('.',phpversion());
    if($phpversion[1] >= 3) {
        header_remove('Set-Cookie'); // php 5.3
    } else {
        header('Set-Cookie:'); // php 5.2
    }        
}

Then I have some additional code that turns this off when the user accepts cookies.

然后我有一些额外的代码可以在用户接受 cookie 时关闭它。

The problem is that there are third party plugins being used in my site that manipulate cookies via javascript and short of scanning through them to determine which ones access document.cookie - they can still set cookies.

问题是我的站点中使用了第三方插件,它们通过 javascript 操作 cookie,并且没有扫描它们以确定哪些访问 document.cookie - 他们仍然可以设置 cookie。

It would be convenient if they all used the same framework, so I might be able to override a setCookie function - but they don't.

如果他们都使用相同的框架会很方便,所以我可能能够覆盖 setCookie 函数 - 但他们没有。

It would be nice if I could just delete or disable document.cookie so it becomes inaccessible...

如果我可以删除或禁用 document.cookie 使其变得无法访问,那就太好了...

EDIT: It is possible to prevent javascript access to get or set cookies.

编辑:可以阻止 javascript 访问以获取或设置 cookie。

document.__defineGetter__("cookie", function() { return '';} );
document.__defineSetter__("cookie", function() {} );

EDIT 2: For this to work in IE:

编辑 2:为了在 IE 中工作:

if(!document.__defineGetter__) {
    Object.defineProperty(document, 'cookie', {
        get: function(){return ''},
        set: function(){return true},
    });
} else {
    document.__defineGetter__("cookie", function() { return '';} );
    document.__defineSetter__("cookie", function() {} );
}

回答by Peter Featherstone

I adapted Michaels codes from here to come up with this.

我从这里改编了迈克尔斯的代码来提出这个。

Basically it uses the defineGetterand defineSettermethods to set all the cookies on the page and then remove the user specified ones, this role could of course also be reversed if this is what you are aiming for.

基本上它使用defineGetterdefineSetter方法来设置页面上的所有 cookie,然后删除用户指定的 cookie,如果这是您的目标,这个角色当然也可以颠倒。

I have tested this with third party cookies such as Google Analytics and it appears to work well (excluding the __utmbcookie means I am no longer picked up in Google Analytics), maybe you could use this and adapt it to your specific needs.

我已经使用第三方 cookie(例如 Google Analytics)对此进行了测试,它似乎运行良好(不包括__utmbcookie 意味着我不再被 Google Analytics 接收),也许您可​​以使用它并根据您的特定需求进行调整。

I've included the part about if a cookies name is not __utmbfor your reference, although you could easily take these values from an array and loop through these that way.

我已经包含了关于 cookie 名称是否不__utmb供您参考的部分,尽管您可以轻松地从数组中获取这些值并以这种方式循环遍历这些值。

Basically this function will include all cookies except those specified in the part that states if( cookie_name.trim() != '__utmb' ) { all_cookies = all_cookies + cookies[i] + ";"; }

基本上,此功能将包括所有 cookie,除了在声明的部分中指定的那些 if( cookie_name.trim() != '__utmb' ) { all_cookies = all_cookies + cookies[i] + ";"; }

You could add to this using OR or AND filters or pull from an array, database, user input or whatever you like to exclude specific ones (useful for determining between essential and non-essential cookies).

您可以使用 OR 或 AND 过滤器添加到其中,或者从数组、数据库、用户输入或您喜欢的任何内容中提取以排除特定的内容(对于确定必要和非必要的 cookie 很有用)。

function deleteSpecificCookies() {

var cookies = document.cookie.split(";");
var all_cookies = '';

    for (var i = 0; i < cookies.length; i++) {

        var cookie_name  = cookies[i].split("=")[0];
        var cookie_value = cookies[i].split("=")[1];

        if( cookie_name.trim() != '__utmb' ) { all_cookies = all_cookies + cookies[i] + ";"; }


    }

if(!document.__defineGetter__) {

    Object.defineProperty(document, 'cookie', {
        get: function(){return all_cookies; },
        set: function(){return true},
    });

} else {

    document.__defineGetter__("cookie", function() { return all_cookies; } );
    document.__defineSetter__("cookie", function() { return true; } );

}

}

回答by Baba

You can not disable it completely but you can override the default setting with .htaccess

你不能完全禁用它,但你可以覆盖默认设置 .htaccess

Try

尝试

 SetEnv session.use_cookies='0';

If it is optional for some users don't use .htaccess

如果对某些用户是可选的,请不要使用 .htaccess

if(!$isAuth)
{
    ini_set('session.use_cookies', '0');
}

回答by Vincent Hoch-Drei

A little bit old but I think you deserve a answer that works:

有点老了,但我认为你应该得到一个有效的答案:

Step 1: Don't execute the third party script code.

第一步:不要执行第三方脚本代码。

Step 2: Show the cookie banner.

第 2 步:显示 cookie 横幅。

Step 3: Wait until user accepts, now you can execute the third party script code..

第3步:等待用户接受,现在您可以执行第三方脚本代码..

Worked for me.

为我工作。

回答by Niet the Dark Absol

How about not paying attention to hoaxes?

如何不注意恶作剧

Aside from the fact that this is old news, the text clearly says that it only applies to cookies that are not essential to the site's function. Meaning session cookies, a shopping basket, or anything that is directly related to making the site work is perfectly fine. Anything else (tracking, stats, etc.) are "not allowed" without permission.

除了这是旧新闻这一事实之外,文本明确指出它仅适用于对网站功能不重要的 cookie 。这意味着会话 cookie、购物篮或任何与使网站正常工作直接相关的东西都非常好。未经许可,其他任何内容(跟踪、统计等)都是“不允许的”。