Control cookies with PHP and JS

The setting of cookies by custom or third-party scripts can be finely controlled using both PHP and JavaScript. Although this is not a sufficient solution for implementing cookie solutions after the court ruling against Planet49 (where it is crucial that tracking tools like Google Analytics do not track data in the first place and therefore do not set any cookies), it can be useful to generally whitelist/blacklist cookies.


This is easy to do in PHP: Here you modify / delete any set cookie headers that have been set . If the following script is called after cookies have been prepared for the response header using setcookie , unwanted headers will be removed and these cookies will not be set in the first place. In addition, cookies set in the past (e.g. if the prevention script did not work for any reason) are also deleted.

8b723b3329c080e9245028b4d0a3fc64

In JavaScript this is a little less trivial: Here we use Object.defineProperty (the powerful successor of __defineGetter__ and __defineSetter__ ) to overwrite the getter / setter methods of the document object, which are always called when cookies are used with the help of document.cookie reads and writes. Object.getOwnPropertyDescriptor receives the original getter / setter, whereby the setter is only called if the cookie is allowed:

8b723b3329c080e9245028b4d0a3fc64

Back