Cookies are a great way to store bits of information about the visitors to your site. You can store things like the users prefered layout or their selections on a shopping site. This page provides functions to get an existing cookie, remove an existing cookie or create a new cookie.
Before you can retrieve or delete a cookie you first need to create one. Below you'll see the code I use to set a cookie.
The setCookie function takes 3 parameters. The name used to reference the cookie, the value to be stored in the cookie and the number of days to keep the cookie for. The days parameter is optional and the cookie will be stored for 28 days if it is omitted.
The setCookie function might be used like this.
If you call the setCookie function with the same cookie name as a cookie that already exists you will overwrite the existing cookie with the new cookie value. We make use of this behaviour later when deleting cookies.
Now that we've got a cookie we need a way to get the value stored in it. I use the getCookie function shown below.
This function takes just one parameter, the name of the cookie to be retrieved. The getCookie function will return the string value stored in the cookie or null if the cookie does not exist.
You could display the value stored in a cookie with this code.
To delete a cookie all we need to do is overwrite the existing cookie with one that has already expired. We could use the setCookie method to do this as shown.
This works by overwriting the existing cookie with one that expired a day ago. This is pretty simple but to keep things clean I tend to use the helper function shown below.
This function does essentially the same thing as using setCookie with a negative day value, but I think the resulting code is easier to follow.
Here's an example of the cookie functions in action. Use the buttons below to set, retrieve and delete cookies.
Cookie Name : | |
Cookie Value : | |
Cookie Duration (days) : | |
Cookie Name : | |
Cookie Name : | |