In HTTP communication, a cookie is a single piece of information with name, value, and
some behavior parameters stored by the server in the client's filesystem or web browser's
memory. Cookies are the de facto standard mechanism through which the session ID is
passed back and forth between the client and the web server. When using cookies, the
server assigns the client a unique ID by setting the Set-Cookie field in the HTTP response
header. When the client receives the header, it will store the value of the cookie; that is, the
session ID within a local file or the browser's memory, and it will associate it with the
website URL that sent it. When a user revisits the original website, the browser will send
the cookie value across, identifying the user.
Besides session tracking, cookies can also be used to store preferences information for the
end client, such as language and other configuration options that will persist among
sessions.
Cookie flow between server and client
Cookies are always set and controlled by the server. The web browser is only responsible
for sending them across to the server with every request. In the following diagram, you can
see that a GET request is made to the server, and the web application on the server chooses
to set some cookies to identify the user and the language selected by the user in previous
requests. In subsequent requests made by the client, the cookie becomes part of the request:
Persistent and nonpersistent cookies
Cookies are divided into two main categories. Persistent cookies are stored on the client
device's internal storage as text files. Since the cookie is stored on the hard drive, it would
survive a browser crash or persist through various sessions. Different browsers will store
persistent cookies differently. Internet Explorer, for example, saves cookies in text files
inside the user's folder, AppData\Roaming\Microsoft\Windows\Cookie, while Google
Chrome uses a SQLite3 database also stored in the user's folder,
AppData\Local\Google\Chrome\User Data\Default\cookies. A cookie, as
mentioned previously, can be used to pass sensitive information in the form of session ID,
preferences, and shopping data among other types. If it's stored on the hard drive, it cannot
be protected from modification by a malicious user.
To solve the security issues faced by persistent cookies, programmers came up with another
kind of cookie that is used more often today, known as a nonpersistent cookie, which is
stored in the memory of the web browser, leaves no traces on the hard drive, and is passed
between the web browser and server via the request and response header. A nonpersistent
cookie is only valid for a predefined time specified by the server.