An HTTP cookie is a piece of data stored by the user's web browser. Unless otherwise specified, cookies can be created, read, modified and deleted both by JavaScript and from server-side through HTTP headers.
An HTTP cookie is a piece of data stored by the user's web browser. Unless otherwise specified, cookies can be created, read, modified and deleted both by JavaScript and by server-side through HTTP headers.
Cookies can be used to remember the state of the session, such as authentication, state of GUI controls and personalization through user preferences. They can also be inappropriately used to track the browsing history and to transfer malware.
A server sets a cookie using Set-Cookie
HTTP header:
Set-Cookie: someName=someValue; Expires=Fri, 18-Jan-2013 10:13:13 GMT
Set-Cookie: someOther=someOtherValue
It is possible to set cookies also on image and similar content that makes them a powerful tracking tool. When cookie is set, it is reported back by the browser:
Cookie: someName=someValue; someOtherName=someOtherValue
For more security, cookies can be restricted to some domain and path:
Set-Cookie: name=value; domain=www.foo.com; Path=/hereonly
They can also have additional secure
(HTTPS only but accessible through JavaScript) and httponly
(HTTP or HTTPS but not accessible through JavaScript) attributes:
Set-Cookie: goldlocation=somewhere; Domain=.morgan.com; secure; httponly
In this example the cookie is accessible for all subdomains of morgan.com but only through HTTPS and not accessible from JavaScript.
Cookie access control is based on domain, (optionally) path and (optionally) URL scheme (http:
vs. https:
). The rules governing cookies are not the same as the access control rules of the DOM in JavaScript which are based on the same domain policy, but because cookie access is mostly based on domain name, they are sometimes confused with the usual HTTP same domain policy.
The behaviour of HTTP cookies in real life browsers is not described in any RFC (thus quoting a RFC to describe cookies is almost always wrong). The various RFC are of historical interest.
Browsers are recommended to allow at least 20 cookies per domain and 4KB per cookie. If you are looking for an alternative to cookies that aren't sent in HTTP headers and can store more data, consider local-storage
Implementation Hint
For jquery fans, there is a simple plugin make it easy to deal with cookies (write, read and delete) could be found here.