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


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 will not be sent to

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.


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:


  • [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. means entire domain while limits the Cookie access to 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:

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.

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:

Retrieving Session in PHP:

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

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.

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

Recommended Articles:

If your learning appetite is still left, you are suggested to read below articles:

Source link

Post a Comment