简体   繁体   中英

How to remove google analytics cookies?

With the new Cookie law i'm trying to find a way i can remove all cookie from my site with a PHP script. I have got a script which works but it doesn't remove google analytics cookie.

How can I remove google analytics cookie?

foreach($_COOKIE as $key => $value) {
      setcookie($key, '', time()-1000);
      setcookie($key, '', time()-1000, '/');
  }

您需要以第5个参数传递域名...

 setcookie($key, '', time()-1000, '/', '.domain.com');

usually firefox shows you whether the cookie was set under www.yourdomain.com or domain.com. In my case the google analytics cookies had been set for domain.com. This code did the job, deleting all 3 Google-related cookies:

foreach ( $_COOKIE as $key => $value ){
if($_POST[$key]==1){
unset($_COOKIE[$key]);
if($key=='language'  || $key=='currency'){
setcookie($key, null, -1, '/', 'www.mydomain.com');
}else if($key=='_ga' || $key=='_gid' || $key == '_gat_gtag_UA_whatever_1' ){
setcookie($key, null, -1, '/', '.mydomain.com');
}else{
foreach ( $_COOKIE as $key => $value ){
if($_POST[$key]==1){
unset($_COOKIE[$key]);
if($key=='language'  || $key=='currency'){
        setcookie($key, null, -1, '/', 'www.mydomain.com');
}else if($key=='_ga' || $key=='_gid' || $key == '_gat_gtag_UA_whatever_1' ){
        setcookie($key, null, -1, '/', '.mydomain.com');
}else{
        setcookie($key, null, -1, '/');
}
$n++;
}
}

I let this run as a form action where I list all cookies stored currently in a client's browser and let him select which one he wants to delete. Those selected come in as $_POST[$key]==1 and are then handled by the script. The not-selected stay alive. This is for an online shop under OpenCart. Needless to say, replace 'mydomain.com' by your's and 'whatever' in the tracking cookie by your google account numbers.

You cant remove a cookie on a clients browser that belongs to a different domain .google, but you could give the user a choice in adding the analytics code.

First step would be use PHP to check for the dnt header [example function] , many browsers already support this + AVG has this as a browser plugin, if its there then default dont add the js code. Or if the dnt header is not set then you can prompt the user about your tracking/analytic cookies, then store there choice in a cookie or a session.

foreach($_COOKIE as $key => $value) {    
    setcookie($key, '', time()-1000, '/', '.domain.com');
}

The above example doesn't work for me - all other cookies are removed leaving only the GA ones. Anyone know why this might be or a better method?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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