Cookies, Sessions, and Local Storage

This article illustrates information on – Cookies, Sessions, and Local storage. It can be helpful for the PHP developer community.

Cookies

How cookies work

Cookies are text files stored on the client’s computer and kept for user-tracking purposes. PHP transparently supports HTTP cookies. Cookie sessions will start with a launch of a browser window and end when the user closes the window. Here are few advantages of cookies, they are useful to track users and know their login information and preferences, and to personalize user sessions by tracking their activities in a website.

There are three steps involved in identifying returning users:

  • The server script sends cookies to the browser—for example, name, age, identification number, etc.
  • Browser stores this information on the local machine for future use.
  • Next time the browser sends any request to the web server, it sends those cookies information to the server and uses that information to identify the user.

Anatomy of a Cookie

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that looks something like this:

HTTP/1.1 200 OK Date: Fri,
04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html

PHP Cookies Set

PHP provides setcookie() function to set a cookie. This function requires up to six arguments and should be called beforetag. For each cookie, this function must be called separately.

setcookie(name, value, expire, path, domain, security);

Here is the detail of all the arguments:

Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.

Value − This sets the value of the named variable and is the content that you want to store.

Expiry − This specifies a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set, then cookie will automatically expire when the Web Browser is closed.

Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.

Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.

Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head><title>Setting Cookies with PHP</title></head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>

Accessing Cookies with PHP

PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.

<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body>
</html>

You can use isset() function to check if a cookie is set or not:

<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>

Deleting Cookie with PHP

<?php setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>

Session

Session variables are stored in an associative array called $_SESSION []. These variables can be accessed during lifetime of a session.

You are working with an application. You open it, make some changes, and then you close it.

When a PHP session is started following things happen −

  • PHP first creates a unique identifier for that session: a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
  • A cookie called PHPSESSID is automatically sent to the user’s computer to store unique session identification string.
  • A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.

Using session

Before you can store information in a session, you have to start PHP’s session handling. This is done at the beginning of your PHP code, and must be done before any text, HTML, or JavaScript is sent to the browser.

To start the session, you call the

// start them engines!
session_start();
// store session data
$_SESSION[“username”] = “Prashant”;

session_start() starts the session between the user and the server, and allows values stored in$_SESSION to be accessible in other scripts later on.

In your second file, you call session_start() again which this time continues the session, and you can then retrieve values from $_SESSION.

// continue the session
session_start();
// retrieve session data
echo “Username = ” . $_SESSION[“username”];

This example is a very basic demonstration of storing and retrieving data in a session. In the first script, the value “Callum” was associated with the key “username” in the $_SESSION array.

In the second script, the information was requested back from the $_SESSION array using the key. $_SESSION allows you to store and retrieve information across the page requests of a user’s active browsing session.

Ending a Session

As important as it is to begin a session, so it is to end one. Even though a session is only a temporary way to store data, it is very important to clean up after yourself to ensure maximum security when dealing with potentially sensitive information.

It is also good practice and will avoid having a huge amount of stale session data on the server.

To delete a single session value, you use the unset() function:

session_start();
// delete the username value
unset($_SESSION[“username”]);

To unset all of the session’s values, you can use the session_unset() function:

session_start();
// delete all session values
session_unset();

Both examples only affect data stored in the session, not the session itself. You can still store other values to $_SESSION after calling them if you so choose. If you wish to completely stop using the session, for example a user logs out, you use the session_destroy() function.

session_start();
// terminate the session
session_destroy();

I highly recommended that when you are sure you no longer need the session that you destroy it usingsession_destroy(), rather than just unsetting all of its values with session_unset().

If you just unset all the value, the session itself is still active and malicious code could give those sessions harmful values.

Local Storage

The LocalStorage API gives front-end web developers access to a simple key-value datastore that can be used to save data on a user’s computer. While considering which is better, local storage vs. session storage, or session storage vs. local storage, local storage object is used to store data in the browser, session storage is good way to improve application performance. A Javascript session storage can be accessed by typing session storage in the browser console.

Saving data on the client side can help speed up your web application’s performance as it can reduce the number of database queries needed on the server. This frees up valuable server resources and can potentially even lead to reduced infrastructure costs.

Before the introduction of LocalStorage, developers who wanted to store data on the client would need to use browser cookies. While this approach did work, it had some problems. Local storage security can be improved by enhancing existing security policies having a incident response plan, encrypting data or by choosing a security vendor.

Local Storage vs. Cookie

he first issue is that a cookie can only store 4,096 bytes of data, which isn’t all that much. Cookies storage is used to store data which can be accessed by server and client. Local storage can store large data. In case of cookie vs. local storage, cookie data is less vulnerable to attacks and is more secure than local storage data.

Another issue is that cookies are sent up to the server with every HTTP request that is made by the client. This increases the size of requests, leading to higher bandwidth usage and slower request times.

LocalStorage is a new technology and therefore, it is important that we test for browser support and consider fallbacks for browsers that do not support the API. Testing for LocalStorage support is very straight forward. All you need to do is create a simple if statement that contains the localStorage interface as the condition. Note the lowercase ‘l’ in localStorage.

The Local storage JavaScript code below shows how you could test to see if a browser supports the LocalStorage API.

if (localStorage) {
// LocalStorage is supported!
} else {
// No support. Use a fallback such as browser cookies or store on the server.
}

If the browser does not support LocalStorage you could fallback to using browser cookies or just send the data to be stored on the server.

Now that you understand how to check for support for LocalStorage lets take a look at what the API has to offer.

Storing Data in LocalStorage

To store data you use the setItem() function. This function takes two parameters, the item key and a value.

localStorage.setItem(‘name’, ‘Prashant Patil’);

Note: There are multiple ways to interact with the localStorage interface.

In this blog post, functions are outlined based on official specifications, but you can also treat the localStorage interface like a JavaScript object or array. The examples below will all store data.

// Functions
localStorage.setItem(‘name’, ‘Prasahnt’);
// Object
localStorage.name = ‘Prasahnt’;
// Array
localStorage[‘name’] = ‘Prasahnt’;

Retrieving Data from LocalStorage

To retrieve data you use the getItem() function. This takes a single parameter; the key that you used when storing data.

var name = localStorage.getItem(‘name’);

Removing Data from LocalStorage

To remove an item from the datastore you use the removeItem() function. This function takes the key of the item that you wish to delete.

localStorage.removeItem(‘name’);

Clearing the Datastore

If you want to delete all of the data in the datastore you can use the clear() function.

localStorage.clear();

Retrieving Keys:
The localStorage interface also includes a function calles key(), that can be used to retrieve the key of a data item using the index (numerical position) of the item in the datastore. Admittedly you will probably not be using this function very often but it is useful to know that it exists.

The JavaScript code below shows how you might use this function to output the keys for each of the items in the datastore.

for (var i = 0; i < localStorage.length; i++) {
console.log(localStorage.key(i))
};

Note the use of localStorage.length in this example. The length property tells you how many items are in the datastore.

Most of the time, people ask whether the session can work if cookies are disabled?

Yes, it works in the following way.

  • It will rewrite all links to pass an extra GET parameter, usually PHPSESSID, but this can be changed by setting session.name in php.ini
  • It will add a hidden input with the same name after all opening tags

FAQs

Is cookie better than local storage?

Cookies are useful in tasks like maintaining user sessions and storing small data, with a size limit of around 4 KB. Local storage, however, offers a larger storage capacity of up to 5MB or more and primarily uses client-side storage.

Which is safer cookies or local storage?

Local storage is the safer one in comparison with cookies because Cookies are encrypted with the secure flag to ensure they are always sent over GTTP connections and can be susceptible to security vulnerabilities. Local storage, on the other hand, is considered to be safer than cookies since it is not a part of each server request, making it less vulnerable.

Why use local storage over cookies?

Storage capacity, client-side processing, security considerations, and domain restrictions are a few top reasons to choose local storage over cookies.

What are the types of sessions in cookies?

Server-side sessions and client-side sessions are the two types of sessions used in cookies.

How long is a cookie session?

A cookie session typically lasts until the user closes the web browser and is referred to as “session cookies” or “non-persistent cookies” due to their temporary existence.