Reputation: 1163
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, '/');
}
Upvotes: 3
Views: 11857
Reputation: 11
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.
Upvotes: 1
Reputation: 93
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?
Upvotes: 0
Reputation: 46610
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.
Upvotes: 2
Reputation: 21531
You need to pass the domain in as the 5th paramater...
setcookie($key, '', time()-1000, '/', '.domain.com');
Upvotes: 7