Definition of HTTP Cookie in the Network Encyclopedia.
On this page:
- What is a HTTP Cookie?
- Persistent Cookies
- Session Cookies
- Secure Cookies
- HTTP-only Cookies
- Same-site Cookies
- How to implement HTTP Cookies
- Setting a cookie
- Creating a Cookie with JavaScript
- Changing a Cookie with JavaScript
- Creating Cookies with PHP
- HTTP Cookies explained in a video
What is HTTP Cookie?
In Internet technologies, a cookie is a text file that a Web server saves on a client machine during a Hypertext Transfer Protocol (HTTP) session. HTTP Cookies are used to record information about the client’s usage patterns, including the date and time the client visited the site, which pages were accessed, Web browser preferences, and so on.
Cookies use the storage system of the client to save this information instead of storing it on the server. Since the vast number of clients might visit the site only once, it would be inefficient to dedicate a large portion of server storage to tracking anonymous clients that might never return. Furthermore, client preferences (such as IP address) might change between sessions, especially for dial-up clients, so servers would have no way of recognizing clients if cookie information were saved on the server.
HTTP Cookies, therefore, provide a way for the server to recognize that the client previously visited the site and record what the client did during previous visits, allowing the server to customize the HTTP session to meet the needs of the client (or the needs of the advertisers of the site!).
Cookies are harmless text files and cannot be used to transmit a virus to the client. Cookies are simply passive holders of information; they cannot be used to «get» any information off your computer (such as your e-mail address). Nevertheless, most Web browsers, such as Chrome or Microsoft Internet Explorer, have an optional setting that allows users to reject cookies.
However, rejecting cookies can result in poorer browsing experiences on sites that are cookie-dependent. You can also delete any cookies on a computer running Microsoft Windows by deleting the contents of the cookies subdirectory within the user profile directory on your hard drive. (Don’t delete the directory itself, however.)
Persistent Cookies
Instead of expiring when the web browser is closed as session cookies do, a persistent cookie expires at a specific date or after a specific length of time. This means that, for the cookie’s entire lifespan (which can be as long or as short as its creators want), its information will be transmitted to the server every time the user visits the website that it belongs to, or every time the user views a resource belonging to that website from another website (such as an advertisement).
For this reason, persistent cookies are sometimes referred to as tracking cookies because they can be used by advertisers to record information about a user’s web browsing habits over an extended period of time. However, they are also used for “legitimate” reasons (such as keeping users logged into their accounts on websites, to avoid re-entering login credentials at every visit).
Session Cookies
A session cookie, also known as an in-memory cookie, transient cookie or non-persistent cookie, exists only in temporary memory while the user navigates the website. Web browsers normally delete session cookies when the user closes the browser. Unlike other cookies, session cookies do not have an expiration date assigned to them, which is how the browser knows to treat them as session cookies.
Secure Cookies
A secure cookie can only be transmitted over an encrypted connection (i.e. HTTPS). They cannot be transmitted over unencrypted connections (i.e. HTTP). This makes the cookie less likely to be exposed to cookie theft via eavesdropping. A cookie is made secure by adding the Secure flag to the cookie.
HTTP-only Cookies
An HTTP-only cookie cannot be accessed by client-side APIs, such as JavaScript. This restriction eliminates the threat of cookie theft via cross-site scripting (XSS). However, the cookie remains vulnerable to cross-site tracing (XST) and cross-site request forgery (XSRF) attacks. A cookie is given this characteristic by adding the HttpOnly flag to the cookie.
Same-Site Cookies
In 2016 Google Chrome version 51 introduced a new kind of cookie, the same-site cookie, which can only be sent in requests originating from the same origin as the target domain. This restriction mitigates attacks such as cross-site request forgery (XSRF). A cookie is given this characteristic by setting the SameSite flag to Strict or Lax.
How to implement HTTP Cookies
Cookies are arbitrary pieces of data, usually chosen and first sent by the web server, and stored on the client computer by the web browser. The browser then sends them back to the server with every request, introducing states (memory of previous events) into otherwise stateless HTTP transactions. Without cookies, each retrieval of a web page or component of a web page would be an isolated event, largely unrelated to all other page views made by the user on the website. Although cookies are usually set by the web server, they can also be set by the client using a scripting language such as JavaScript (unless the cookie’s HttpOnly flag is set, in which case the cookie cannot be modified by scripting languages).
Setting a cookie
Cookies are set using the Set-Cookie
HTTP header sent in an HTTP response from the webserver. This header instructs the web browser to store the cookie and send it back in future requests to the server (the browser will ignore this header if it does not support cookies or has disabled cookies).
As an example, the browser sends its first request for the homepage of the www.networkencyclopedia.com
website:
GET /index.html HTTP/1.1 Host: www.networkencyclopedia.com ...
The server responds with two Set-Cookie
headers:
HTTP/1.0 200 OK Content-type: text/html Set-Cookie: theme=bluesky Set-Cookie: sessionToken=xyz003; Expires=Wed, 02 Jun 2021 12:15:28 GMT ...
The server’s HTTP response contains the contents of the website’s homepage. But it also instructs the browser to set two cookies. The first, “theme”, is considered to be a session cookie since it does not have an Expires
or Max-Age
attribute. Session cookies are intended to be deleted by the browser when the browser closes. The second, “sessionToken”, is considered to be a persistent cookie since it contains an Expires
attribute, which instructs the browser to delete the cookie at a specific date and time.
Next, the browser sends another request to visit the spec.html
page on the website. This request contains a Cookie
HTTP header, which contains the two cookies that the server instructed the browser to set:
GET /spec.html HTTP/1.1 Host: www.networkencyclopedia.com Cookie: theme=bluesky; sessionToken= xyz003 …
This way, the server knows that this request is related to the previous one. The server would answer by sending the requested page, possibly including more Set-Cookie
headers in the response in order to add new cookies, modify existing cookies, or delete cookies.
Creating a Cookie with JavaScript
JavaScript can create, read, and delete cookies with the document.cookie
property.
With JavaScript, a cookie can be created like this:document.cookie = “username=John Doe”;
You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed: document.cookie = “username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC”;
With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.document.cookie = “username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/”;
Reading a Cookie with JavaScrip
With JavaScript, cookies can be read like this: var x = document.cookie;
document.cookie
will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;
Changing a Cookie with JavaScript
With JavaScript, you can change a cookie the same way as you create it: document.cookie = “username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/”;
The old cookie is overwritten.
For more information about handling cookies read the w3schools.com tutorial about JavaScript Cookies.
Creating Cookies with PHP
To generate HTTP cookies in PHP, you need to utilize the built-in setcookie()
function. This function is responsible for dispatching a cookie as part of the HTTP headers. Due to protocol restrictions, it’s important to remember that cookies, like other headers, must be set before your script produces any output. This means that you’ll need to place setcookie()
function calls before generating any output, which includes before <html>
and <head>
tags or any form of whitespace in your script.
After successfully setting the cookies, you’ll be able to retrieve them during subsequent page loads through the $_COOKIE
array. Additionally, these cookie values can also be found in the $_REQUEST
array.
To better understand Cookies in PHP and see examples visit PHP documentation – function setcookie.