n00bly
n00bly

Reputation: 395

Disable cookies until user accepts them via javascript

Is there a way to disable the cookies (when a visitor visits a website) and only enable them after the visitor gives permission for it? And all with javascript or php.

In the EU there are new rules that requires this permission from a visitor. When you visit a site, only cookies that collects analytics results like Google analytics may be enabled without permission. But when you use Google tag manager for remarketing and things like that, you should have it disabled on your site with a notification bar on top where the visitor can give permission to enable them.

Is there a way to make this happen with javascript or PHP or a combination of both?

Regards, Robert

Upvotes: 1

Views: 3138

Answers (1)

symcbean
symcbean

Reputation: 48387

Yes - its not hard....

 <?php
 ob_start();
 if (!count($_COOKIE) && !$_REQUEST['i_will_accept_cookies']) {
     // user has not accepted cookies
     include($message_about_cookies);
     ini_set('session.use_cookies', 0); // make sure later code doesn't drop them by accident
     // Even if not using sessions, it provides a convenient place
     // to store the user preferences for the duration of execution
     // NB you should also poll this setting before calling setcookie()
 } else {
     // user accepts cookies
     if (!count($_COOKIE)) {
         setcookie("i_accept_cookies", "", time() + 3600*24*7);
     }
     // session_start(); // uncomment if using sessions
     // ini_set('session.use_cookies', 1); // only required
                 // if you've got 0 in the config files
 }

You can run the above as an auto-prepend.

Your message about cookies should contain a link/form/script which sends the 'i_accept_cookies' message back to the server.

Upvotes: 1

Related Questions