Setting cookies for EU legislation

Recently on the Textpattern forum a community member asked about writing code to display a warning that cookies are being set in order to comply with EU legislation.

The requirement was to allow the user the option to remove the warning message in the future using PHP instead of JavaScript.

The code explained

The returned value of the contained statement populates the cookie named cookie_warning_visible. It will either contain a string ‘true’ or ‘false’ depending on whether the warning is hidden or not. It is marked as hidden and the TXP variable contains ‘false’ if a cookie named cookie_warning_hidden exists.

The code

<txp:variable name="cookie_warning_visible"><txp:php>
	/**
	 * Checks if the HTTP GET or POST request
	 * contains 'hide_cookie_warning' parameter. E.g.
	 * http:example.com/?hide_cookie_warning=1.
	 *
	 * If it does, it proceeds to create a new cookie using
	 * PHP's setcookie() function. The cookie is named
	 * cookie_warning_hidden, contains value '1' and is set to
	 * expire in a year.
	 *
	 * The gps() function that is used to check the HTTP param
	 * existence is from Textpattern. The function can be used
	 * to return any HTTP POST or GET param by name.
	 *
	 * The PHP block outputs 'false' using echo language construct.
	 */

	if (gps('hide_cookie_warning'))
	{
		setcookie('cookie_warning_hidden', 1, strtotime('+1 year'), '/');
		echo 'false';
	}

	/**
	 * If not doing the above 'hide_cookie_warning', it
	 * checks if a cookie already exists.
	 *
	 * The check is done using Textpattern's cs() function.
	 * The function can be used to get any cookie from
	 * the HTTP request by name.
	 *
	 * Outputs 'false' if true.
	 */

	else if (cs('cookie_warning_hidden'))
	{
		echo 'false';
	}

	/**
	 * If neither of the above comes true, it finally
	 * outputs to 'true'.
	 *
	 * If neither condition evaluates true, it means
	 * that the cookie doesn't exists and the warning
	 * is not set hidden.
	 */

	else
	{
		echo 'true';
	}
</txp:php></txp:variable>

The above code that sets the variable would ideally be saved in a form, and then included on each page using output_form, e.g:

<txp:output_form form="cookie_monster" />

The following uses normal variable tag to check the above variable’s value.

<txp:variable name="cookie_warning_visible" value="true">
	<div id="cookie-monster">
		This website places cookies on your computer to help ma [...]
		<a href="?hide_cookie_warning=1">Hide this warning</a>
	</div>
</txp:variable>

Note: The above code has not been tested thoroughly but can form the basis for your final code.

Further information on the forum. To find more information specifically about the few Textpattern functions mentioned above, search for gps() or cs() in the txplib_misc.php file: Textpattern code

comments powered by Disqus