1. Home
PHP

PHP Tutorials : A Comprehensive Guide

Master PHP with our in-depth tutorials. From beginner to advanced topics, explore essential concepts and upskill yourself.

  • 7
  • 1
right-top-arrow
3

Cookies in PHP

Updated on 03/10/2024348 Views

The advent of the internet brought about the use of cookies, which have greatly improved user experience as well as facilitated more personalized interaction on the web. The concept of cookies was first introduced in 1994 by Lou Montulli, an engineer at Netscape Communications.

Today, cookies are used everywhere. Statistics show that nearly every website you visit relies on cookies in some form or another to tailor content, track user behavior, and facilitate seamless navigation.

PHP programming languages use cookies for saving and retrieving information and therefore application developers can develop dynamic and interactive web applications. To make user experiences richer, we can use PHP to exploit cookie features that come with the language. This unlocks a variety of avenues for customization and personalization.

In this guide, I will explain everything about cookies in PHP, look at how to set and retrieve cookies in PHP, and much more.

Overview

Cookies are small pieces of data that help servers remember information from previous interactions with us. When we make our first request to a server, it sends back a response that includes a tiny parcel of data known as a cookie. This data is stored on our machine as a text file. Then, whenever we return to that site, our browser automatically includes these cookies in its request headers, allowing the server to recognize us.

Cookies are seamlessly integrated into PHP. Using PHP's built-in functionality, we can effortlessly set and retrieve cookies to enhance user experiences on our website. In PHP, the setcookie() method lets us inject cookies into our server's responses. This means we can easily access, modify, or delete cookies as needed.

This guide will detail everything regarding working with cookies in PHP, including how to set them, access them, and even handle their deletion.

What are Cookies in PHP and How Can We Create One?

Cookies in PHP are little packets of data that the web server stores on our computer to remember certain information. 

When we visit a website, let's say an online store, we log in with our username. The site will then use a cookie to remember our username for the next time we drop by, making our experience more personalized. Developers often use cookies and sessions in PHP. The cookie session PHP helps them to manage user data and maintain state across web applications.

Cookies have their boundaries. They can only be read from the domain they're issued from. So, when we are browsing "example.com," cookies from "example.com" are fair game, but not from any other domain.

Creating a Cookie in PHP

Creating or setting a cookie in PHP is done with the setcookie() function. It can also be used to represent “PHP add cookie” or “create cookie in PHP”. Before any output from the script, we can call setcookie() to generate our cookie. Here is the syntax:

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

Let's break down the syntax of setcookie():

  • name: The name of the cookie
  • value: The value associated with the cookie
  • expire: This is the cookie's expiry time (optional)
  • path: The path on the server for which the cookie will be available (optional)
  • domain: The domain for which the cookie is available (optional)
  • security: Indicates whether the cookie should be sent only over secure HTTPS connections (optional).

Here is a cookie PHP example

For example, let’s say we are running a blog site, and we want to customize the content based on the user's preferred language. Cookies can help achieve just that. Say we want to set a cookie named "User_Language" to store the user's preferred language choice, such as "en" for English or "es" for Spanish. We can use the following PHP code for that:

<!DOCTYPE html>

<?php

// Set a cookie to store user's language preference

  

setcookie("User_Language", "en", time() + (86400 * 30), "/"); // expires in 30 days

?>

<html>

<body>

<?php

     echo "Cookie is created."; // Display a message to confirm cookie creation

?>

<p>

<strong>Note:</strong>

     You may need to reload the 

     page to see the value of the cookie.

</p>

</body>

</html>

In the code snippet above;

  • We use setcookie() to create a cookie named "User_Language" with the value "en" (English)
  • The cookie is set to expire after 30 days, specified by adding the current time to 30 days in seconds (86400 seconds in a day).
  • The cookie is available for the entire website ("/")

With the PHP cookie set, the next time the user visits our blog, the website can check the "User_Language" cookie and customize the content accordingly, providing a seamless and personalized experience.

Types of Cookies in PHP

When it comes to cookies in PHP, you'll encounter two main types:

  • Session Cookie: These cookies are temporary and have a short lifespan. They expire as soon as our session ends, which typically happens when we close our browser. Session cookies are often used for tasks like maintaining your login status during our browsing session.
  • Persistent Cookie: Unlike session cookies, persistent cookies stick around for a longer period. We can set an expiration time for them, and they remain valid until that time is reached or until the user manually deletes them. Persistent cookies are handy for tasks where we want to remember user preferences or login information across multiple sessions. 

Cookies Operations in PHP

When it comes to handling cookies in PHP, there are some things we should know. Let's walk through some essential cookie operations that one should know.

1. Checking if a Cookie is Set or Not

Before using a cookie's value, it's always smart to check if it even exists. To do this in PHP, we use the trusty isset() function. Let's say we want to see if a cookie named "Auction_Item" is set. Here's how we should do it:

<!DOCTYPE html>

<?php

setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);

?>

<html>

<body>

<?php

if (isset($_COOKIE["Auction_Item"]))

{

     echo "Auction Item is a " . $_COOKIE["Auction_Item"];

}

else

{

     echo "No items for auction.";

}

?>

<p>

<strong>Note:</strong>

     You might have to reload the page 

     to determine the cookie's value.

</p>

</body>

</html>

In the example above, PHP checks if the "Auction_Item" cookie is set. If it is, it echoes out the item's description (in this case, a luxury car). Otherwise, it lets us know there are no items up for auction.

2. Accessing Cookies with PHP

Once we have confirmed that a cookie exists, we can access its value. PHP gives us a couple of handy ways to do this. We can use either $_COOKIE or $HTTP_COOKIE_VARS variables. Let's say we have cookies named "name" and "age" set. Here's how we can access their values:

<?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["age"] . "<br />";

?>  

This code snippet above shows how to access the values of cookies named "name" and "age" using $_COOKIE.

3. Deleting Cookies

Sometimes, it's time to bid farewell to a cookie that has served its purpose. To delete a cookie or perform “php clear cookie” or “unset cookie php”, we simply set it with an expiration date in the past, prompting the browser to remove it automatically. Here is an example code:

<?php

   // Deleting the 'username' cookie 

setcookie("username", "", time() - 3600);

   echo "<h2>Cookie 'username' is now removed</h2>";

?>

In the example above,

  • "cookie_name" is the name of the cookie that has to be deleted.
  • "" represents an empty value for the cookie. This effectively removes the content of the cookie.
  • time() - 3600 causes the browser to delete the cookie from storage by setting the cookie's expiration date to a past date. The - 3600 indicates a time in the past, effectively deleting the cookie immediately.
  • echo "<h2>Cookie 'cookie_name' is now removed</h2>"; is an optional message that can be displayed to confirm that the cookie has been deleted. This is useful for providing feedback to users or for debugging purposes.

4. Storing a Cookie

When we have to remember something important for our website users, like their preferences or login status, storing a cookie comes in handy. PHP makes it super simple to do this. For instance, let's say we are running a blog and we want to remember a user's preferred theme. This data can be kept in a cookie in the following manner:

<?php

   $theme = "dark"; // Assume user prefers a dark theme 

setcookie("theme_preference", $theme, time() + (86400 * 30), "/");

   echo "<h2>Cookie 'theme_preference' is now stored</h2>";

?>

5. Modifying Cookie Values

Life is all about change, and sometimes we need to update those cookies accordingly. Suppose readers of our blog like to change from a dark to a bright theme. To accomplish this, we may change the cookie value as follows:

<?php

   $theme = "light"; // User decides to switch to a light theme 

setcookie("theme_preference", $theme, time() + (86400 * 30), "/");

   echo "<h2>Cookie 'theme_preference' value has been updated</h2>";

?>

In this updated code:

$theme now holds the new value for the cookie, in this case, 'light'.

setcookie() is used again to update the cookie's value with the new theme preference.

Practical Examples of When to Use Cookies in PHP 

When it comes to PHP development, knowing when to use cookies can greatly enhance our website's functionality and user experience. Let's discuss some scenarios where cookies are commonly used and how they can benefit our PHP projects.

User Authentication

Cookies are frequently employed in user authentication systems. After a user logs in to our website, we can set a cookie containing a session identifier or user token. This cookie allows us to recognize the user as authenticated on subsequent page visits without requiring them to log in again.

For example, consider a social media platform where users log in once and then freely navigate between different pages without constantly re-entering their credentials. Behind the scenes, cookies are managing their authentication status, providing a seamless experience.

<?php

// Upon successful login, set a cookie with a session identifier

$session_id = generate_session_id(); // Assume this function generates a unique session ID

setcookie('session_id', $session_id, time() + 3600, '/');

?>

Customized Content

Cookies are invaluable for delivering personalized content to users. We can use cookies to remember user preferences, such as language settings, theme choices, or preferred product categories. This enables us to tailor the content dynamically based on each user's preferences.

Let's say we run an e-commerce site. By storing a cookie with the user's preferred product categories or past purchases, we can suggest relevant items or display targeted advertisements, enhancing the user's shopping experience. Here is an example code:<?php

// Store user's language preference in a cookie

$language = $_POST['language']; // Assume language preference is obtained from a form submission

setcookie('user_language', $language, time() + (86400 * 30), '/');

?>

In the code above, the user's selected language is stored in a cookie named 'user_language'. This cookie remains valid for 30 days and ensures that the website can display content in the user's preferred language during subsequent visits.

Shopping Carts

Cookies are commonly employed in e-commerce websites to maintain the state of a user's shopping cart across multiple page views. When a user adds items to their cart, we can store this information in a cookie. This way, even if the user navigates to different pages or closes the browser, their shopping cart remains intact.

Think about online retail giants like Amazon. As we browse through products, add items to our cart, and continue shopping, cookies silently keep track of our selections, ensuring a seamless shopping experience from start to finish.

<?php

// Add item to shopping cart and store in a cookie

$item_id = $_POST['item_id']; // Assume item ID is obtained from a form submission

$cart = isset($_COOKIE['shopping_cart']) ? unserialize($_COOKIE['shopping_cart']) : array();

$cart[$item_id] = $item_details; // Assume $item_details contains information about the item

setcookie('shopping_cart', serialize($cart), time() + (86400 * 30), '/');

?> 

Tracking User Activity

Cookies are also used for tracking user activity and behavior on websites. By storing unique identifiers or tracking codes in cookies, we can monitor how users navigate our site, which pages they visit most frequently, and where they spend the most time.

Consider a news website that wants to analyze reader engagement. By utilizing cookies to track which articles users read and how long they spend on each page, the website can tailor its content strategy to better meet readers' interests and preferences. Here is an example code;

<?php

// Track user activity and store in a cookie

$page_visited = 'homepage'; // Assume the current page visited is the homepage

$activity_log = isset($_COOKIE['activity_log']) ? unserialize($_COOKIE['activity_log']) : array();

$activity_log[] = array('page' => $page_visited, 'timestamp' => time());

setcookie('activity_log', serialize($activity_log), time() + (86400 * 30), '/');

?>

 This code snippet above tracks the user's activity by logging the pages they visit along with timestamps. The information is stored in a cookie named 'activity_log', which is updated and retained for 30 days.

In all of these situations, cookies step up to the plate, acting as a super helpful tool for keeping track of user sessions, customizing content, and making our website work like a charm. It's super important to handle cookies with care, always keeping user privacy front and center. That means being upfront about how we are using cookies and making sure to follow all the rules and regulations, like GDPR.

When we use cookies wisely in our PHP projects, we are not just making things easier for ourselves, but creating a more fun and friendly experience for our website visitors.

Conclusion

In conclusion, cookies serve as fundamental components in shaping our online interactions. They allow websites to remember user preferences, streamline navigation, and deliver personalized content. Throughout this guide, we've explored the basic operations involved in managing cookies in PHP, including setting, accessing, modifying, and deleting them as necessary.

It's important to handle cookies with care, ensuring user privacy and compliance with relevant regulations such as GDPR. Trust and confidence among website visitors can be built by maintaining transparency regarding cookie usage and periodically clearing outdated data.

There is no doubt that cookies in PHP provide a valuable tool for creating user-friendly web experiences tailored to individual needs.

FAQs

  1. What is a cookie in PHP?

A cookie in PHP is a small piece of data stored on the user's computer by a web server. It's commonly used to remember user preferences or track user activity across different pages.

  1. Where are cookies stored in PHP?

Cookies in PHP are stored on the user's computer as text files. These files are typically stored in the browser's cache or temporary internet files folder.

  1. Why are cookies used?

Cookies are used in PHP to enhance user experience by remembering user preferences, maintaining user sessions, and personalizing content. They also help track user behavior and gather information for website analytics.

  1. What is an example of a cookie?

An example of a cookie in PHP could be a website remembering a user's login credentials so they don't have to log in every time they visit. Another example could be a website storing a user's language preference to display content in their preferred language.

  1. How to create cookies?

To create cookies in PHP, we can use the setcookie() function. This function allows us to specify the name, value, expiration time, path, domain, and security settings for the cookie.

  1. How to destroy a cookie in PHP?

 To destroy a cookie in PHP, we can set its expiration time to a past date using the setcookie() function. This will prompt the browser to remove the cookie from storage.

  1. Why is it called cookies?

The term "cookie" originated from the idea of a small piece of data being exchanged between a web server and a web browser, similar to how a fortune cookie contains a message inside a small package. The term was coined by programmer Lou Montulli in 1994 while working at Netscape Communications.


Talk to Career Expert
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .