HTTP Cookie

Overview

Cookies are used to implement features such as the following.

  • Record and display how many times a visitor has visited the page.
  • Record a visitor’s recently visited page in a web service and show that page on the next visit.
  • Record the username entered in a bulletin board or chat so the user can skip entering it next time.
  • Maintain a login session.

The following specifications are published.

This kind of data can be recorded on the server side using CGI and similar mechanisms, but cookies can also record cookie information on the client-side hard disk, meaning the side where the browser runs.

The file where cookie information is stored depends on the OS and browser version.

For example, on Windows it may be recorded in folders or files such as:

- C:\Document and Settings\(UserName)\Cookies
- C:\Program Files\Netscape\Users\(UserName]\cookies.txt
- C:\Program Files\Netscape\Navigator\cookies.txt
- C:\Windows\Cookies\~.txt

For Chrome on macOS, it is stored under:

- ~/Library/Application Support/Google/Chrome/Default/Cookies

Writing Cookies

When setting a cookie with JavaScript:

document.cookie = "~";

To specify it with HTML, use the following. This method is not recommended.

<meta http-equiv="Set-Cookie" content="~">

The ~ part specifies a string in the following format.

NAME=value; expires=value; domain=value; path=value; secure

Everything except NAME=value; is optional.

Parameter Meaning
NAME=value Specifies the desired value for the desired name. Semicolons, commas, spaces, and Korean text must be encoded in an appropriate format. URL-style encodings such as %3B, %2C, and %20 are often used.
expires=value Specifies the expiration date of the cookie recorded on the client side in a format such as Thu, 1-Jan-2030 00:00:00 GMT. The time zone is always GMT. If omitted, it expires when the browser closes. If a past value is specified, the cookie is deleted.
domain=value Specifies the name of the web server that publishes the cookie. If omitted, it becomes the web server name, such as www.devkuma.com.
path=value When browsing a page matching this path name, the browser sends the stored cookie information to the server.
secure If this variable is included, cookie information is sent only when the connection to the server is secure.

The simplest writing example is as follows. It is valid until the browser ends and is sent to pages in the same folder or lower layers as the page where it was set.

Set-Cookie: NAME=devkuma;

Specifying an expiration date:

Set-Cookie: NAME=devkuma; Tue, 31-Dec-2030 23:59:59;

Reading Cookies

To read cookie values with JavaScript, refer to document.cookie.

alert(document.cookie);