How to remove google analytics cookies?

All QuestionsCategory: QuestionsHow to remove google analytics cookies?
SagarSagar Sharma asked 2 years ago

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, '/');
  }
1 Answers
Best Answer
Josh PriceJosh answered 2 years ago

usually firefox shows you whether the cookie was set under http://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.