Home Notes Web development How to set a cookie using PHP or JavaScript

How to set a cookie using PHP or JavaScript E-mail
Friday, 22 January 2010 12:27

In my jQuery Woopra plugin, I have added the feature to exclude visits by cookies.  Since Woopra does not yet have the ability to set cookies itself like Google Analytics, you must set it yourself.  Thankfully it's pretty easy to do.  Below I will show you how to set a cookie to use with the jQuery Woopra plugin to exclude visits based on that cookie.

Place the following within <?php and ?> tags in a PHP file.

 
$value = 'true';
setcookie('woopraExclude', $value, time()+(365*24*60*60))
 

The code above sets a cookie with:

  1. name = woopraExclude
  2. value $value = 'true'
  3. expiration = current time plus one year

This is the method I use on my sites.  I've placed the code below in a plain HTML file that loads as the start page on all my browsers, ensuring that all my visits to my own domains don't count as visits in analytics.

To set a cookie with JavaScript, I recommend using the webtoolkit.cookies.js script that comes bundled with the jQuery Woopra plugin.  To set a cookie using that script, place the following within <script type="text/javascript"> and </script> tags:

 
var Cookie = new CookieHandler();
var excludeCookie = Cookie.setCookie('woopraExclude','true',365*24*60*60);
 

The code above sets a cookie with:

  1. name = woopraExclude
  2. value $value = 'true'
  3. expiration = current time plus one year

To make use of this cookie in your Woopra analytics code, you would initialize your Woopra tracking function as:

 
$.trackWoopra({cookie: 'woopraExclude'});