Difference between Session and Cookies

Key Difference between Session and Cookie

  • Sessions are server-side files that contain user information, whereas Cookies are client-side files that contain user information.
  • Session is dependent on Cookie, but Cookie is not dependent on a session.
  • A Session ends when a user closes his/her browser, while a Cookie expires depending on the lifetime you set for it.
  • You can store as much data as you like in a Session, but the data storage space in a Cookie is only 4KB.
  • All the registered data within a session can be destroyed using the Session_destroy() command. However, there is no such command as unsetcookie() to remove data from a cookie.  

Difference between Session and Cookies
Difference between Session and Cookies

Here, I have analyzed the difference between Session and Cookie and will comprehensively evaluate their pros and cons.

What is a Session?

A session is a global variable stored on the server. Each session is assigned a unique ID, which is used to retrieve stored values. Whenever a session is created, a cookie containing the unique session ID is stored on the user’s computer and returned with every request to the server. If the client browser does not support cookies, the unique session ID is displayed in the URL. Sessions have the capacity to store relatively large amounts of data compared to cookies.

The session values are automatically deleted when the browser is closed. If you want to store the values permanently, you should store them in the database.

Just like the $_COOKIE array variable, session variables are stored in the $_SESSION array variable. Similar to the cookies, the session must be started before any HTML tags.

Why and when should I use Sessions?

Sessions are used to pass values from one page to another. They store important information, such as the user ID, more securely on the server, where malicious users cannot tamper with it.

It is also used when you want an alternative to cookies on browsers that do not support cookies, to store global variables in an efficient and more secure way. It is better than passing them in the URL or when developing an application such as a shopping cart that temporarily stores information with a capacity larger than 4KB.

Creating a Session with PHP

To commence a session, you need to initiate the session_start function in PHP and subsequently save your values in the $_SESSION superglobal array.

Consider the scenario where you want to track the frequency of page visits. Utilizing a session is an effective method for this purpose.

The following example demonstrates how to establish and access values in sessions:

<?php

session_start(); //start the PHP_session function 

if(isset($_SESSION['page_count']))
{
     $_SESSION['page_count'] += 1;
}
else
{
     $_SESSION['page_count'] = 1;
}
 echo 'You are visitor number ' . $_SESSION['page_count'];

?>
Output:
You are visitor number 1

Advantages of Session

Here are the advantages of the session from my perspective.

  • Enhances user interaction by maintaining a continuous dialogue state across multiple requests.
  • Reduces server load by temporarily storing user data.
  • Improves security through controlled data exposure for limited durations.
  • Allows personalized experiences based on user behavior and preferences.
  • Facilitates complex transactions by keeping track of multiple steps.
  • Increases website performance by minimizing the need to re-authenticate.
  • Supports scalability by managing user sessions effectively across distributed systems.

Disadvantages of Session

In my experience, these are the drawbacks of using sessions.

  • Increases the risk of data breaches if session data is intercepted.
  • Consumes server memory, potentially decreasing overall system performance.
  • It can lead to inconsistent user experiences if improperly managed.
  • Requires additional server resources to maintain and monitor sessions.
  • Session expiration can disrupt user activities, causing frustration.
  • Vulnerable to session hijacking and fixation attacks.
  • It may complicate compliance with privacy regulations due to persistent data storage.

What is a cookie?

A cookie is a small file with a maximum size of 4KB that the web server stores on the client computer. Once a cookie has been set, all page requests that follow return the cookie name and value. A cookie can only be read from the domain that it has been issued from. For example, a cookie set using the domain www.guru99.com cannot be read from the domain career.guru99.com. Most of the websites on the internet display elements from other domains, such as advertising. The domains serving these elements can also set their own cookies. These are known as third-party cookies. A cookie created by a user can only be visible to them. Other users cannot see its value. Most web browsers have options for disabling cookies, third-party cookies, or both.

Why and when should I use Cookies?

HTTP is a stateless protocol; cookies allow us to track the state of the application using small files stored on the user’s computer. The path where the cookies are stored depends on the browser. Internet Explorer usually stores them in Temporal Internet Files folder.

Personalizing the user experience: This is achieved by allowing users to select their preferences. The page requests that follow are personalized based on the set preferences in the cookies. Tracking the pages visited by a user.

Creating Cookies with PHP

Now, let’s delve into the fundamental syntax needed for cookie creation.

<?php

setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]);

?>
  • In PHP, the setcookie function is utilized to generate a cookie. The “cookie_name” represents the identifier for the cookie, which is essential for the server when it needs to fetch the cookie’s value from the $_COOKIE array. This name is mandatory.
  • The “cookie_value” denotes the cookie’s content and is also required.
  • The “[expiry_time]” parameter is optional and can be set to dictate the lifespan of the cookie, like setting it to expire in 1 hour. This is done by adding or subtracting seconds from the PHP time() function, for example, time() + 3600 to set 1 hour.
  • The “[cookie_path]” is another optional parameter that determines the server path where the cookie is accessible. Using a forward slash “/” indicates that the cookie is available across the entire domain, whereas specifying subdirectories restricts access to those subdomains.
  • The “[domain]” parameter, also optional, establishes where the cookie can be accessed. For example, setting it to www.cookiedomain.com makes it available across the entire domain, whereas www.sub.cookiedomain.com restricts it to that subdomain and its child subdomains. Remember, a subdomain can also have its own subdomains as long as the total length of the domain does not exceed 253 characters.
  • The “[secure]” parameter is optional, with its default setting being false. It specifies whether the cookie should be transmitted over HTTPS (if true) or HTTP (if false).
  • The “[Httponly]” setting is optional as well. When set to true, the cookie cannot be accessed by client-side scripting languages such as JavaScript .

Note: The PHP setcookie function must be called before any HTML tags are outputted.

Let’s consider a practical example involving cookies.

In this case, we’ll develop a simple program that stores a username in a cookie set to expire after ten seconds.

The following “cookies.php” code demonstrates how to implement this.

<?php
     setcookie("user_name", "Guru99", time() + 60,'/'); // expires after 60 seconds
     echo 'the cookie has been set for 60 seconds';
?>
Output:
the cookie has been set for 60 seconds

Advantages of Cookies

From my experience, here are the benefits of cookies:

  • Enhances the element of surprise in flavor discovery.
  • Offers a minimalist aesthetic, ideal for modern branding.
  • Reduces packaging clutter, focusing attention on the product.
  • Eliminates bias based on ingredient preferences or brand perception.
  • Encourages tasting without preconceived notions, leading to unbiased feedback.
  • Potentially lowers printing costs for packaging.
  • Simplifies regulatory compliance in markets with less stringent labeling laws.

Disadvantages of Cookie

Based on what I have seen, these are the disadvantages of cookies.

  • Customers cannot identify allergens or dietary restrictions.
  • Lacks nutritional information, which is important for health-conscious consumers.
  • Misses the opportunity to highlight unique or premium ingredients.
  • It may cause confusion among similar products on the shelves.
  • Prevents brand recognition and loyalty building.
  • Detracts from informed consumer decision-making.
  • This could lead to legal issues in regions with strict labeling laws.

Session vs Cookie: Difference Between Them

Here are the important differences between a session and a cookie that I have observed in my practice:

Session vs Cookie
Session vs Cookie

Session
Cookie

Sessions are server-side files which contain user information

Cookies are client-side files that contain user information

A session ends when a user closes his browser

Cookie ends depending on the lifetime you set for it

In PHP, before using $_SESSION, you have to write session_start(); Likewise for other languages

You don’t need to start the cookie as it is stored in your local machine

Within a session, you can store as much data as you like. The only limit you can reach is the maximum memory a script can consume at one time, which is 128MB by default

The official maximum cookie size is 4KB

A session is dependent on Cookie

A cookie is not dependent on the Session

Session_destroy() is used to destroy all registered data or to unset some

There is no function named unsetcookie()

Conclusion

I recommend using sessions when the data security and capacity requirements exceed what cookies can offer. However, cookies are unbeatable for ease of use and for implementing lightweight, persistent user state tracking.