Sunday, 9 June 2019

PHP Cookies and Sessions | Detailed Explanation | Coding Examples

In this article, we would be discussing the Concepts like Sessions and Cookies in great depth with Coding Examples in PHP. We would be seeing the differences between Sessions and Cookies in PHP. We would also be learning how to set Sessions and Cookies in PHP through Coding Examples.

PHP Cookies and Sessions | Detailed Explanation | Coding Examples
PHP Cookies and Sessions | Detailed Explanation | Coding Examples







Suggested Read: Redis vs MySQL Benchmarks


Introduction:

In this section, we would be discussing the very basics of Cookies and Sessions, and it would form the much-needed foundation for us to understand the differences between Sessions and Cookies and how they are implemented in PHP.

What are Sessions:

When you browse through a website in logged in state, how the Internet (or HTTP to be more specific) knows or recognizes you? We all know that HTTP is a stateless protocol and hence it does not manages the state of a particular user and to do that, we need Sessions.

Suppose you are using Facebook like billions of other individuals, whenever you visit a page on Facebook, each time the client sends a new request to Facebook Server and Facebook, being served over HTTP can't distinguish that whether the request is coming from you or some other user.

How can we solve this problem? The solution is to use Sessions. Session variables store the information (e.g. username, favorite food e.t.c) of a user across multiple pages. As a matter of fact, Session variables are stored on Server Side and only a unique identifier called Session-Id referring to that Session gets stored on Client Side inside a Cookie.

What are Cookies:

A Cookie is nothing but a small piece of text stored on a user's computer by their browser. Some of the common use cases for Cookies are authentication, storing of site preferences e.t.c. It is stored on Client Side Computer in a text file format with a size limit of 4KB. The Cookie information is passed to the web server by the user's web browser each time it interacts with a web server.

Once a Cookie has been set, all the requests were sent with that Cookie. As a matter of fact, only those Cookies stored by the browser that relate to the domain in the requested URL will be sent to the server. This means that cookies that relate to www.abc.com will not be sent to www.abcd.com.

For Example, have a look at the following screenshot of a real Cookie stored on a Client's Machine:

PHP Cookies and Sessions | Detailed Explanation | Coding Examples
PHP Cookies and Sessions | Detailed Explanation | Coding Examples

You can see in this image, a Cookie with the unique identifier (Session ID) being stored as content.

Workflow:

So what happens when you visit a website, Facebook for example? Let's See:

Suppose, you want to access Facebook and you hit the URL for the first time from your browser. For the sake of simplicity, let us also assume that you have never visited the Facebook from your current machine (i.e, computer/laptop) in the past, this is the first time you have ever visited Facebook from your current machine. Now, when you login into Facebook, Facebook's Server would generate a unique identifier (i.e, Session ID) and it gets stored on Facebook's Server.

Then the same Session ID gets stored on your machine as well in a Cookie. Now, for each of the following HTTP requests for Facebook, that Cookie is also sent to Facebook's server where it simply fetches the Session ID from the Cookie and matches that with the Session ID stored on Facebook's Server. If it matches, You are allowed to visit the page otherwise you would be directed to the Facebook's Login page. This is the simplest use case of Cookies and Sessions.



Differences Between Session and Cookies in PHP:


Basis for Comparision Cookies Sessions
Storage Side Cookies are stored on the Client side Sessions are stored on the Server side
Data Size Limit A Cookie can be of maximum 4KB in size A Session has no such limit on the size
Security Cookies are not much secure as they travel with each and every HTTP request Sessions are way more secure as they don't travel with HTTP requests
Usability for Future Reference A Cookie can be used for future references, For example, Shopping Carts A Session can't be used for future references
Common Use Cases
  • The page requested that follow are personalized based on the set preferences in the cookies.
  • Personalizing the user experience.
  • Tracking the pages visited on a website by a particular user.
  • You want to store important information such as the user id more securely on the server where malicious users or hackers cannot tamper with them.
  • You are developing an application such as a shopping cart that has to temporary store information with a capacity larger than 4KB.
  • You want to pass values from one page to another. (Example: Multi-Page Forms).



Coding Examples in PHP | Cookies:

In this section, we would be discussing how to create, retrieve and delete the Cookies in PHP.

Set Cookie in PHP | Creating Cookies in PHP:

<?php
    setcookie([cookie_name], [cookie_value], [expiry_time], [cookie_path], [domain], [secure], [httponly]);
?>

Where,
  • [cookie_name](Mandatory): Name of the Cookie that the server will use when retrieving its value from the $_COOKIE array variable.
  • [cookie_value](Mandatory): The value of the Cookie. (It is Session ID in case of Sessions).
  • [expiry_time](Optional): It can be used to set the expiry time for the Cookie such as 30 minutes. The time is set using the PHP's time() function plus or minus a number of seconds greater than 0 i.e. time() + 1800 for 30 minutes.
  • [cookie_path](Optional): It can be used to set the Cookie path on the server. The forward slash “/” means that the Cookie will be made available on the entire domain.
  • [domain](Optional): It can be used to define the Cookie access hierarchy i.e. www.abcdomain.com means entire domain while www.sub.abcdomain.com limits the Cookie access to www.sub.abcdomain.com and its subdomains.
  • [secure](Optional): It is used to determine whether the Cookie is sent via https if it is set to true or HTTP if it is set to false. Its default value is False.
  • [Httponly](Optional): If it is set to true, then only client-side scripting languages i.e. JavaScript cannot access them.

Note: the PHP set cookie function must be executed before the HTML opening tag.


Retrieving Cookie in PHP:

<?php
     print_r($_COOKIE);    //It would print the Complete $_COOKIE variable from which you can fetch required Cookie values 
?>


Unset Cookie in PHP | Deleting Cookie in PHP:

The Cookie would get automatically destroyed once its expiry time is over, but if you want to destroy the Cookie before it expires, you can simply set the Cookie's expiry time again with to a time which has already passed, in this way the Cookie would obviously get deleted.

<php setcookie([cookie_name], [cookie_value], time() - 360); ?>



Coding Examples in PHP | Sessions:

In this section, we would be discussing how to create, retrieve and delete the Sessions in PHP.

Set Session in PHP | Creating Sessions in PHP:

To Create Session variables, you just need to add values to a $_SESSION variable. Now, suppose you want to track particular page views using Session:

<?php

session_start(); //To use Sessions, you need to insert call this PHP function 

if(isset($_SESSION['pageCount'])) {
     $_SESSION['pageCount'] += 1;
} else {
     $_SESSION['pageCount'] = 1;
}
?>


Retrieving Session in PHP:

You just need to fetch the value from $_SESSION array.

<?php

session_start(); //To use Sessions, you need to insert call this PHP function 

if(isset($_SESSION['pageCount'])) {
     echo $_SESSION['pageCount']; 
}
?>


Unset Session in PHP | Deleting/Destroying Session in PHP:

As a matter of fact, in most of the cases, the default Expiration time for a Session Variable is 24 Minutes. If you want to modify the default Expiration time, you can follow this link: Modify Session Default Expiration Time.

<?php

session_start(); //To use Sessions, you need to insert call this PHP function 

//If you want to unset a particular Session Variable
if(isset($_SESSION['pageCount'])) {
     unset($_SESSION['pageCount']); 
}
?>

//If you want to destroy Complete Session Variable
session_destroy(); //session_destroy removes all the session data including cookies associated with the session.
?>


Liked this blog? Don't miss out on any future blog posts by Subscribing Here

No comments:

Post a Comment

Labels

JavaScript (9) PHP (7) MySQL (5) Arrays (3) Elasticsearch (3) Laravel (3) variables (3) Beats (2) ELK stack (2) Kibana (2) Logstash (2) SQL (2) functions (2) Benchmark (1) CakePHP (1) Callbacks (1) Cluster (1) CodeIgniter (1) Cookies (1) DBMS (1) Documents (1) Frameworks (1) HTTP (1) HTTP Status Codes (1) Indices (1) InnoDB (1) Learning (1) MyISAM (1) Nodes (1) OTP (1) Redis (1) Replication (1) Roadmap (1) Searching (1) Sessions (1) Sharding (1) Storage Engines (1) Symfony (1) Twilio (1) Ubuntu (1) books (1) expired time (1) let (1) remember me (1) var (1)