What are cookies?
When the world wide web was first invented and began to move towards dynamic content, an obvious problem with the HTTP protocol was discovered--it was a stateless protocol by default, meaning it didn't keep track of people or sessions. This meant that it was difficult to have secure web applications that required logins. Cookies were intended as the solution. They are essentially little pieces of data a web server sends to your browser and has it store. Your browser sends it back to the web server in every request after, allowing the web server to be able to keep track of you. This made secure sessions possible. A user would authenticate to a web server, the server would generate a session token, store it in a database, and send it to the browser to store in a cookie. The browser would send it back to the web server with every request, and the web server could verify the user is authorized to access protected resources.
Implementation in HTTP
A cookie is always set by the server first in an HTTP response. The response sets the cookie using the Set-Cookie header, and must use one Set-Cookie header per cookie being set.
HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: theme=light
Set-Cookie: sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT
In this example server response, two cookies where set. The first has a key called theme and the value is light. This is an example of how cookies might be used to personalize a light theme setting on a website Because an expiration date was not specified for this cookie it will expire at the end of the users session, which is usually interpreted by the browser. The second cookie set has a key called sessionToken and the value stored was abc123. This cookies was set to expire June 9, 2021 at 10:18 GMT
When the browser sends requests to the website in this session, it will pass along these cookies automatically like so:
GET /spec.html HTTP/1.1
Host: www.example.org
Cookie: theme=light; sessionToken=abc123
...
The server would respond with more Set-Cookie headers to make new, update, or remove existing cookies. To remove a cookie a server needs to set an expiration date for the cookie in the past.
Expiration Dates
Cookies have an expiration date and time, and its not possible to create a cookie without one. This is for security reasons. It ensures that regular authentication to an application is required and thereby increases security. For example, when you log in to your bank on a browser of any kind, a session id of some form is stored in a cookie. If that cookie was set to never expire, anyone could simply open up your banking website after you walked away and have access--you would stay logged in forever.
Scope
The domain and path of a cookie tell the browser where the cookie belongs too and when the cookie should be submitted. For security reasons, a website can only set a cookie for its domain and subdomains. i.e. example.com and subdomains.examples.com.
Other Attributes
Cookies can have other attributes. There are httpOnly cookies, which are cookies that can't be accessed programmatically via the document.cookie API (which we'll learn about in the next section)
How To Make Cookies in JavaScript
In this tutorial we'll use developer tools on our browser and interact with the console to run the following JavaScript tutorial. To open developer tools, simply press Ctrl+Shift+I or right click the page and select the Insepct option. You should see a confusing looking panel that looks something like the following screenshot to the bottom or the left of your screen:
Next find the console tab:
And open it up:
All of the JavaScript commands showcased in this tutorial can be typed and ran in the console by pressing enter. Try it out and experiment! You won't break anything.
You can access cookies via the DOM API in JavaScript. Cookies can be accessed in the document.cookie method. You can create a cookie as below:
document.cookie="username=Kai;"
Even thought the assignment operator is being used, cookies are actually being appended to the document.cookie object. When I run:
document.cookie="username=Kai;"
document.cookie="theme=light;" // appends, doesn't overwrite
console.log(document.cookie);
This outputs:
username=Kai; theme=light
You update a cookie using the same syntax:
document.cookie="username=Jeff;"
console.log(document.cookie);
This outputs:
username=Jeff; theme=light
The cookie api intelligently recognizes you are updating the value in the username key when you use this syntax.
You use this syntax to add expiration dates:
document.cookie="logged_in=yes; expires=Fri, 17 Oct 2025 23:00:00 MST;"
And you can set a path that the cookie belongs to:
document.cookie="logged_in=yes; path=/"
And you set the domain in the same way:
document.cookie="logged_in=yes; domain=example.com"
To delete a cookie you just need to set the cookies date to a past date. You don't need to specify a value:
document.cookie="logged_in=; expires=Thu, 16 Oct 2025 00:00:00 MST;"
How To Make Cookies in PHP
Setting up a PHP server is beyond the scope of this tutorial but a docker container with a little walkthrough can be provided here. Once you've started the docker container with the docker compose file you can edit the PHP code in hello.php and view the server at http://localhost:4000/hello.php
Setting a cookie in PHP simply requires the setcookie function. It takes a few parameters. We'll focus on the name, value, expires_or_options, and domain parameters. The documentation of setcookie is included in the references section where all of the parameters can be seen. Basic usage is as so:
$value = "Kai";
setcookie("user", $value);
We can set expiration like so:
$value = "Kai";
$tomorrow = time() + 86400;
setcookie("user", $value, $tomorrow);
We can set the path and the domain like so:
$value = "Kai";
$tomorrow = time() + 86400;
setcookie("user", $value, $tomorrow, "/", "example.com");
To read the cookies, we use the $_COOKIE object. To access a specific cookie we use the key as its index and access it as an object like so:
$username = $_COOKIE['username']; // "Kai"
To delete a cookie we must set the expiration date to be a time in the past, so we can conveniently do it like this (you don't need to specify the value):
setcookie("username", "", time() - 3600);
Resources
https://www.w3schools.com/js/js_cookies.asp - This is a great resource that details the syntax for performing all of the operations discussed in this blog post. It shows you concisely how to store information in a cookie, set expiration, and set the domain scope.
https://www.w3schools.com/js/js_cookies.asp - This is a great resource that details the syntax for performing all of the operations discussed in this blog post. It shows you concisely how to store information in a cookie, set expiration, and set the domain scope.
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie - This is a great resource because mozilla.org is the officially recognized documentation for Web APIs and all other web standards like HTML, CSS, JavaScript, etc. I think the section at the bottom that shows compatability across browsers is particularly useful. Also, right above that it shows what cookies look like in an HTTP form.
https://www.php.net/manual/en/function.setcookie.php - This is the official documentation for PHP, this page specifically for setting cookies. It details all of the parameters in the setcookie function and has some more examples on how to use it!
Web page designed by ChatGPT, content created by me.