how to set and unset cookies from webpages using Javascript or PHP
An HTTP Cookie or Web Cookie is a small piece of data that is send from the web server to the client browser that can be stored in the client machine for a future look ups.The cookies were primarily designed as a mechanism to maintain a session state of the user sessions without too much network and/or server traffic.
There are several good uses of cookies, although it has got a lot of bad press because of misuses by websites and concerns about user privacy. HTTP Cookies can be used to maintain any information as long as it is text, such that the user shopping cart, authentication details etc.
If you are developing a website, then it is quite possible that you will need to set cookies on the user client. Of course, the exact requirements of the website will dictate whether you need a cookie at all, but let's assume that you want to learn how to set and unset cookies from webpages.
No matter what framework you use, you can set cookies using simple JavaScript on your page. This is independent of the JS library you might be using such as Dojo or JQuery. Having said that, there are several libraries available that are supposed to ease the pain of managing the cookies.
A cookie can contain associated meta information along with the value of the cookie. There are some required values, while many are not required and defaults to reasonable or appropriate value when setting the cookie. The general syntax (or spec) of an HTTP cookie is as shown below.
A cookie is set by using the HTTP request header Set-Cookie. The value of this header is the entire cookie that will be parsed and saved in the client browser.
Set-Cookie: name=value;Comment=comment;Domain=domain;Max-Age:time-in-seconds;Expires=expiry-time;Path=path;Secure;Version=1
Name: This is the name of the cookie. This can be any string that uniquely identifies the cookie. You will need this later if you want to read the value.
Value: This is the value of the cookie. This can at-most be around 4kb. The 4093 byte limit is for the entire cookie, but assuming a reasonable size for other fields, we can specify that the value can have at-most of about 4000 bytes.
Comment: An optional field that is rarely used. You specify a string that explains why and what the cookie is used for.
Expires: The expires field sets the exact time when the cookie is set to expire or become invalid. The time is set using the format Wdy, DD Mon YYYY HH:MM:SS GMT
Max-Age: Another way to specify the expiration time. It specifies the time interval in seconds, which is calculated from the time the cookie is set. If both Max-Age and Expires is set, then Max-Age takes preference.
Path: You can optionally set the path of the webpage that the cookie is set for.
Domain: You can also explicitly set the domain name for which this cookie is set for. If not specified, then the defaults to the domain that requested the URL.
Secure: No value need to be specified here. Adding the keyword Secure to the cookie will make sure that only secure and encrypted connections such as HTTPS is used to set the cookie.
HttpOnly: The cookie can set and accessed by using only http connections. Other methods such as Javascript calls will not be able to access the cookie.
A complete example of a cookie string will be something like:
Set-Cookie:mycookiename="this cookie value";Domain=.example.com;Max-Age=3600;Path=/;Secure
JavaScript
You can set cookies using a JavaScript function. A very simple function to set cookie will look something like this:
<script> function setCookie(cKey, cValue, age) { if (!age || age === null) { age = -1; } document.cookie = cKey + "=" +cValue + ";Max-Age="+age; } </script>
You can now call the function using the various arguments from anywhere in the website. A valid call to set a cookie that is expires in an hour will be like
setCookie("CookieName", "Cookie value is not important", 3600);
On a side note, setting the max-age to a negative value will make it to be somewhat of a session cookie, with the browser deleting the cookie when the browser session ends. In order to delete or unset the cookie, call method with the key (or name) of the cookie and 0 (zero) as the age. Setting the max-age to zero instead of a negative value will remove the cookie.
setCookie("CookieName", "", 0);
PHP
If you are using PHP as your server-side scripting language, then you can set cookies using the setcookie(…) function. The function has the following syntax.
bool setcookie(name, value, expires, path, domain, secure, httponly)
A quick example is
setcookie("CookieName", "this cookie value", time()+3600, "/", "mydomain.com");
Note that the setcookie(…) method takes the expires as the argument, and not max-age. You will need to set the time at which you want the cookie to expire rather than the time interval as shown in the JavaScript example.
As with the JavaScript, you can unset or delete the cookie by setting the expires field to a time and date in the past. A value of 1 for the expires field will do the trick.
JQuery
You can use the standard JavaScript functions as shown above to set cookies. There is also plugins available in JQuery that allow you to set and unset cookies using JQuery like syntax. One of the popular plugin is jquery-cookie.
First include the plugin in your webpage…
<script src="/path/to/jquery.cookie.js"/>
You can then call the plugin code to easily set a cookie. The expires field takes the value in number of days. If you want to set the expiration to anything smaller, then you will need to use the JavaScript date object.
$.cookie("CookieName", "This is the cookie value", {expires : 1, path: "/" });
In order to remove a cookie, you can call the removeCookie(…) method with the exact parameters that you used to create it in the first place.
$.removeCookie("CookieName", {path: "/"});
Dojo
As with JQuery, Dojo also provides a useful library to manage your cookies. The syntax in Dojo is eerily similar to that of the JQuery plugin.
cookie(cookieName, cookieValue, cookieProps);
You can use it as shown in the example below
require(["dojo/cookie"], function(cookie){ // To set a cookie cookie("CookieName", "My Cookie Value", {expires: 10}); });
In order to delete the cookie, you set the expires field value to -1.
In general, cookies can be removed or unset by setting an expiry date in the past. This is probably a good idea as compared to other methods that try to explicitly overwrite JS objects etc. This allows the browser to expire and remove the cookies much more gracefully, thus making your code more browser and implementation agnostic.
Some General Tips
As you work with cookies more and more, you will realize that it can quickly get to be a nightmare where you can assume nothing and will have to deal with every single scenario. You can follow certain "good" programming techniques that will reduce the headaches.
Use only when necessary: The use of cookie should warrant a good return in terms of feature or performance. For example, it might save several server round trips. No Critical Data: Avoid setting any critical data in the cookies. Remember that cookies are easy to be read by other programs or websites. Never set any critical data, such credit card info or social security number even if it is encrypted. Never Trust the Cookie: Never trust the data that comes back in a cookie. Remember that cookies can very very easily be spoofed, so it is always important to validate and authenticate the information from the cookies before consuming it. Also, always validate the data that comes back in the cookie before doing any server side operations. No Executable Code: Please do not store and pass around code that you want to execute later. That is not what it is for. Building mechanisms to parse and execute code stored in cookies is really really bad. Yeah, i have seen it way too many times. Set Expiration Dates: It is good practice to set a reasonable expiration date on the cookie. It is pretty cheap to create, update or recreate the cookie. That is better than having to do housekeeping such as having to delete or unset cookies to remove data. I have too often seen cookies that does not expire for another 10 years. Set Value to Empty: If and when you have to explicitly reset or remove cookies, also set the cookie to null or empty string. This also wipes the data that is already there. If in case, you happen to read the cookie again during the session, you will not get a stale value. Unreliable Data: It is quite possible for the user to reject cookies from websites on the client side. It is generally not a good idea for you to rely on the existence of the cookie to provide any critical features of the website. Cookies should be treated as a luxury and used to enhance the website rather than to rely on them completely to provide website features.