The difference between cookies, local storage and sessions
Why it's so important for aspiring developers to know about this
I remember the first time I set cookies with my PHP code. It was to log users in after they have registered. At that time I was new to coding and I was very excited to see how my codes actually worked. I had a eureka moment by using cookies. According to my naïve old self, my users could now sign up and log in safely by using cookies. At least, I thought that my users were safe but I was so wrong.
<?php
//database_connection.php
$connect = new PDO("mysql:host=localhost;dbname=testing2", "root", "");
?>
<?php
//login.php
include("database_connection.php");
if(isset($_COOKIE["type"]))
{
header("location:index.php");
}
$message = '';
if(isset($_POST["login"]))
{
if(empty($_POST["user_email"]) || empty($_POST["user_password"]))
{
$message = "<div class='alert alert-danger'>Both Fields are required</div>";
}
else
{
$query = "
SELECT * FROM user_details
WHERE user_email = :user_email
";
$statement = $connect->prepare($query);
$statement->execute(
array(
'user_email' => $_POST["user_email"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$result = $statement->fetchAll();
foreach($result as $row)
{
if(password_verify($_POST["user_password"], $row["user_password"]))
{
setcookie("type", $row["user_type"], time()+3600);
header("location:index.php");
}
else
{
$message = '<div class="alert alert-danger">Wrong Password</div>';
}
}
}
else
{
$message = "<div class='alert alert-danger'>Wrong Email Address</div>";
}
}
}
?>
These are the exact codes that I have used.
Since I was working on a medical software, my cookie based approach to log users in has raised some eyebrows and I had to get the talk about safety and security from team leads and project managers. I was told that using cookies for storing passwords and user information is not a safe practice. I was told that my codes did not adhere to the guidelines of something called the HIPAA laws. In the world of medical software development it is imperative that all codes are always HIPAA compliant. The Health Insurance Portability and Accountability Act of 1996 are the national standards to protect sensitive health information from being disclosed without the patient's knowledge and consent. The law requires the best security practices in these three areas: administrative, physical security and technical security. Every software created for the health care industry must be HIPAA compliant and I almost violated that by using cookies to store user information. There are three main ways of storing data in a browser through local storage, session storage and cookies. Before talking about the differences, let's talk about the similarities. All three are actually stored on the user's browser that the user is actually using. The user can open a different browser and the information or data from the previous browser's cookies, local storage and sessions will not exist in this browser. These are also only stored in the user's computer and no where else. Cookies however, are completely different than local storage and sessions.
Cookies
HTTP cookies, also known as internet cookies, browser cookies or simply cookies are small chunks of data created by a web server while a user is browsing a website. Cookies can serve useful services on the web. Items added to a cart or shopping items etc stateful information as such can be the result of cookies. Whenever you are filling out a form, cookies are often triggered to fill out the entire form automatically.
Authentication Cookies
Authentication cookies are commonly used by a web browser to authenticate if a user is logged in. The security of an authenticated cookie depends on the security the web server is providing. Security vulnerabilities can allow a cookies data to be read by an attacker and get compromised.
Tracking Cookies Tracking cookies are third party cookies. Tracking cookies can be used to track user's long term browsing history. These cookies have triggered privacy concerns across the globe. These cookies contain tracking software that tracks, stores and retrieves important information about us. We always agree to lengthy license agreements without reading and hence giving website owners the permission to track us.
Although cookies do make browsing experience much better. It comes with costs of privacy and it can be used by cyber criminals to impersonate the user online and gain access to user's accounts. Cookies are traditionally set by server side coding but they can also be set by JavaScript.
document.cookie = "username=John Doe";
You can also add an expiration date for the cookie.
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2021 12:00:00 UTC";
We can also delete the cookie from the browser by setting the parameter to a past date.
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Cookies can only store 4KB of data on client side. For modern front-end applications this may be inadequate.
Local storage in a browser
Local storage was an overall improvement to cookies. Local storage allows us to keep data with much more storage space than cookies provide. We can keep 5MB of data with local storage which is a massive improvement. Local storage stores everything in a key/value form. Just like cookies local storage can only store strings as data. Unlike cookies our data isn't sent to the server when an HTTP request is made. The local storage stores data with no expiration date. The data will not be deleted if the browser is closed. But the data can be removed using JavaScript or it can be cleared from cache by deleting browser history. The syntax for storing data with local storage is:
localStorage.setItem(keyname, value)
Try it with these codes:
localStorage.setItem("mytime", Date.now());
To remove all data stored in local storage you can write the following codes
localStorage.clear();
It is absolutely necessary to convert JavaScript objects to strings with Json.stringify() before saving. While retrieving data from local storage we can convert them back with Json.parse(). But while developing a software for the healthcare industry, I was told to never save sensitive information using local storage as well. So now I had to master sessions.
Sessions There are many similarities between sessionstorage and localstorages such as they are both web storage objects and they are both an improvement to cookies. They both provide greater storage capacities of 5MB. Data from both is not sent back to the server for every HTTP request which reduces the traffic between client and server greatly. But local storage stores everything with no expiration date. The information is available for any user who visits the same website using the same PC and the same browser. All information stored in local storages are saved and made available for current and future visits to the site. But in sessions all the data is deleted once user closes the browser. Session storage is unique per tab so once the tab is closed all information stored in the session is deleted. I can see why session storage can be a safer way to log users in versus local storage or cookies. So it also makes sense why companies like udemy or godaddy who wants the users to stay logged in would use local storage versus healthcare industries and government agencies would prefer session storage over local storage. It also makes sense why cookies are slowly becoming a very antiquated way of storing data in a browser. Although local storage information can also be used by third parties to track browsing history many rules and regulations have been put into place since the cookie monster has raised security alerts. A session is started with the code for server side coding:
session_start()
Sessionstorage can be created with JavaScript and also with server side coding. Sessions are also stored in key value pairs. Syntax for session storage in JavaScript is as follows.
sessionStorage.setItem(keyname, value)
Setting items in sessions with JavaScript
sessionStorage.setItem("test1", "Lorem ipsum");
Setting items in sessions with server side scripting language such as PHP. Local storages however would always need to be set with JavaScripting. But sessions can be set with server side coding.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
Although cookies do not remain a preference anymore due to the high alert it has raised over security issues. Both local storages and session storages remain a preference today depending on what the client side needs. Do they want to stay logged in even after the browser closes or do they need to be logged out for security issues.