+91-20-4078-9067 info@niyuj.com

Cookies, Sessions and Local storage:

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

Cookies :

Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies.

There are three steps involved in identifying returning users

1.Server script sends a set of cookies to the browser. For example name, age, or identification number etc.

2.Browser stores this information on local machine for future use.

3.When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.

Prashant Patil

Associate Technical Architect

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 look 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
Setting Cookies with PHP:

PHP provide setcookie() function to set a cookie. This function requires upto six arguments and should be called beforetag. For each cookie this function has to 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 actually want to store.

Expiry − This specify 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 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 −

1. PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.

2. A cookie called PHPSESSID is automatically sent to the user’s computer to store unique session identification string.

3. 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 to 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
session_start()

<?php
// 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.

<?php
// 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 sitting on the server.

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

<?php
session_start();
// delete the username value
unset($_SESSION["username"]);

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

<?php
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.

<?php
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 users computer. Saving data on the client-side can help to speed up the performance of your web applications as it can reduce the number of database queries that are 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 that wanted to store data on the client would need to use browser cookies. While this approach did work it had some problems. The first issue is that a cookie can only store 4,096 bytes of data, which isn’t really all that much. 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.

Checking for Browser Support :

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 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 I use the functions outlined in the official specification, 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 this question can session work if cookies are disabled?
Yes, it work using following way.
1. 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

2. It will add a hidden input with the same name after all <form> opening tags.

Note : that this is a dangerous thing to do, because anyone who you e.g. copy/paste a URL to containing an PHPSESSID parameter will be able to share your login session on the site – the webserver has no easy way of telling that you are different from the person you sent the link to.