Control cookies with PHP and JS

The setting of cookies by your own or third-party scripts can be finely controlled with the help of PHP and JavaScript. Although this is not a sufficient solution for the implementation of cookie solutions after the court ruling against Planet49 (here it is crucial that tracking tools such as Google Analytics do not even track and consequently do not set cookies), it can make sense be 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.


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: