C is for cookies …

July 20, 2009 by nuno costa 1 comment Stumble It del.icio.us

Are you hungry ?
let’s eat some cookies

Those brown things with chocolate ?

Well, not really. Cookies are an easy and fast way for an web site to store information pertinent to it’s visitor, like the items in the shopping cart or the your layout preferences

So, no chocolate ?

A cookie is a text file automatically stored by your browser in your computer, nothing more than that, sorry but there is no magic!

Aren’t those things bad ?

Well since a cookie is stored in a text file, it’s no too difficult to read it, that is why trusting cookies with your credit card number or password is a bad idea much the same way you ( hopefully ) don’t write your passwords in a post it and stick it in the monitor.

Even if you encrypt the data it’s still not a good idea, poorly written web sites usually store a cookie with the user id, so if some one get that cookie can impersonate you, but authentication using cookies is a theme for another day

The important message is never store sensitive data in a cookie!

Give me more !

One of the drawbacks of HTTP protocol is that it’s stateless meaning the server does not remember you from one page to another, so relevant information must be sent over and over again!

So the process is:

  • The browser detects a cookie for that domain and send it
  • The web server receives the cookie maybe do some changes and returns it to the browser

Let me explain you the basics of HTTP protocol, so you can actually understand cookies and why they must be sent before any html (this is a very simple and incomplete explanation, just enough to allow you to understand the cookies mechanics, so don’t even bother to flame me with spec’s about HTTP)

The communication between the browser and the web server obeys an rigid format, en each communication two blocks of data are sent

  • The header block
  • The data block

The header can contain information about the action expected from the server or the server’s response code and also the cookie data

By now you should ha guessed it the data block contains the actual data such as the HTML page requested

Another peculiar trace about the HTTP protocol is that it is not spooled meaning the request/response is sent as soon as it is created, so you must send the cookie data before sending any HTML

Php comes with a set of functions that allow us to spool the request and only send it when we want or when the script is finished, they are called Output Buffering Functions

The following code will fail because we are trying to send a cookie after starting to send the data block
for it to work we must activate the output buffering

I want one!

Now that we now about the cookie mechanics and a little about the HTTP protocol lets start sending and receiving cookies with php. I

Sending cookies

We have two functions to send cookies setCookie and setRawCookie, both work the same way but setCookie will urlencode the cookie value. Since this is the only difference we will only talk about setCookie
setCookie syntax:

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]] );

The most used parameters are:

  • name
  • value
  • expire

Be aware that expire is an Unix timestamp (the number of seconds since epoch) so when setting the expiration date we give the number of seconds since January 1, 1970 until the desired expiration date. time() + 60 will expire the cookie 60 seconds from now
If we leave it empty the cookie expires when the session ends (when you close the browser window), please note that on modern browsers with tabbed browsing the session ends when you close the browser window not the tab!
If you remember cookies are sent with each request/response, so you set cookies in the response and get cookies in the request this means that if you set an cookie it will become available with the next request

Reading cookies

You can read a cookie value trough the super variable $_COOKIE, its just an associative array with all the cookies the browser sent

$myCookye = $_COOKIE['myCookie']

Deleting a cookie

There is no deleteCookie function you just set a new cookie!
A cookie is deleted if is value is False or an empty string but only if it was defined exactly the same way as when you set it meaning only value and expire can be different
Since a cookie is deleted if its value is false is advisable not to use booleans as cookie value use 0 or 1 instead

Wrap it all up

='))
			? setcookie($name, $value, $expire, $path, $domain, $secure, $httponly)
			: setcookie($name, $value, $expire, $path, $domain, $secure);
 
	}
 
	/**
	 *  @param $name String - the cookie name
	 *  @return Mixed - the cookie value
	 */
	public static function get($name){
		if( key_exists($name, $_COOKIE) ){
			return htmlentities($_COOKIE[$name],ENT_QUOTES, Config::get('Site/Charset'));;
		}else{
			return false;
		}
	}
	/**
     * Delete a cookie, name path and domain must match the original values
     *
	 * @param $name String - the cookie name
	 * @param $path String - the cookie path
	 * @param $domain String - the cookie domain
	 * @return boolean - True on success
     */
	public static function remove($name, $path = NULL, $domain = NULL){
		return Cookie::set($name, '', -86400, $path, $domain, NULL, NULL);
	}
}
?>

Let me know what you think, leave a comment

1 comment so far Add Your Comment

  1. by C is for cookies … | Adobe Tutorials on July 31 2009 at 11:34

    [...] Are you hungry ? let’s eat some cookies Those brown things with chocolate ? Well, not really Original post: C is for cookies … [...]

More from francodacosta.com

© francodacosta.com - All rights reserved