Cookies in PHP: Create, Retrieve, Delete

In this tutorial, we will explore in detail how to create, read, and handle cookies in PHP with examples. When you are building a modern and dynamic web application, it is often necessary to store small pieces of information on the client side to improve the user experience, maintain state across multiple sessions, and remember user preferences.

For these purposes, PHP provides a powerful feature called cookies. So, before diving into the implementation, let’s first understand what a cookie is in PHP.

What are Cookies in PHP?


A cookie is a small text file sent by a web server to the user’s browser and stored locally on the client’s machine. In simple terms, a cookie is a small piece of data stored on the client’s machine by the web server. It helps a website to recognize and remember a user during future visits.

Cookies are commonly used to store and retrieve information, such as:

  • Login credentials (username or email)
  • Shopping cart items
  • User preferences (language, theme, layout)
  • Session tracking data

Each time the same computer requests a page with a browser, it will automatically send the cookie. In PHP, you can easily create, access, update, and delete cookies using built-in functions.

How to Create Cookies in PHP?


PHP provides a built-in function called setcookie() that is used to create a cookie in the user’s browser. This function sends a cookie from the server to the client, where it is stored locally.

Basic Syntax for Setting a Cookie in PHP

setcookie(name, value, expire, path, domain, secure, httponly);

Parameters:

The setcookie() function accepts seven parameters:

  • name → Name of the cookie (must be unique).
  • value → Value to be stored in the cookie.
  • expire → Defines the expiration time of the cookie in seconds. By default, if not set, the cookie will expire when the browser is closed.
  • path → Defines the server path where the cookie will be available. (Default is /, which means the cookie is available across the entire domain).
  • domain → Domain for which the cookie is valid (e.g., scientecheasy.com).
  • secure → If set to true, the cookie will only be transmitted over secure HTTPS connections.
  • httponly → If set to true, the cookie is accessible only through HTTP(S) and not via JavaScript, which helps prevent XSS attacks.

Example 1: Setting a Cookie in PHP

<?php
$cookie_name = "user";
$cookie_value = "John Smith";
setcookie($cookie_name, $cookie_value, time() + 3600, "/"); // Expires in 1 hour.
echo "Cookie has been set successfully!";
?>
Output:
      Cookie has been set successfully!

This is a basic example of setting a cookie in PHP. In this example, we have created a cookie named user with the value “John Smith”. This cookie is set to expire after one hour, as indicated by time() + 3600. Here, the time() function in PHP returns the current time in seconds.


By adding 3600 to this timestamp, you are saying that the cookie will expire in one hour (3600 seconds = 60 minutes = 1 hour). After this period, the cookie will automatically remove and will no longer be available. The “/” sets the path for which the cookie is available for the entire site. You can also select the directory you want.

Important Note:

  • Cookie values must always be strings.
  • If you want to save an array or something associative, you must convert the data to be a string and then save it in the cookie.

How to Retrieve Cookie Data in PHP?


In PHP, once a cookie has been set in the user’s browser, it is automatically sent back to the server with every subsequent request until the cookie expires or is deleted. To read and access these cookies on the server, PHP provides the $_COOKIE superglobal array that we use.

What is $_COOKIE in PHP?

The superglobal variable $_COOKIE in PHP is an associative array that contains all cookies sent by the browser in the current request. It stores cookie data as key–value pairs, where the array key represents the cookie name and the associated value represents the cookie’s stored value.

Example: Create and Retrieve Cookie (cookie.php)

<?php
$cookie_name = "user";
$cookie_value = "John Smith";
setcookie($cookie_name, $cookie_value, time() + 3600, "/");
?>
<!DOCTYPE html>
<html>
<head>
    <title>Example of setting and retrieving Cookies</title>
</head>
<body>
<?php
// Checking whether the cookie is set using isset() function.
if (isset($_COOKIE[$cookie_name])) {
  // If the cookie "user" exists, print its value,
     echo "Cookie " . $cookie_name. " is set! <br>";
     echo "Value is: " . $_COOKIE[$cookie_name]; // Accessing cookie's value.
} else {
  // If the cookie is not found (first load or expired).
     echo "Cookie named" .$cookie_name. "is not set!";
 }
?>
</body>
</html>

In this example, we have set a cookie named “user” with the value “John Smith” using setcookie() function. This cookie will expire after 1 day (86400 seconds = 24 hours). The parameter “/” indicates that the cookie is available across the whole domain.


Then, we have used the isset() function to check whether a cookie exists before trying to access it. It is good practice to verify that it exists to avoid errors or warnings. The superglobal variable $_COOKIE[$cookie_name] returns the value of the cookie named “user”.

If the user cookie exists, it displays a welcome message “Cookie user is set!” and the cookie’s value on the browser. Otherwise, it displays a message “Cookie named user is not set!” on the browser.

Output on first page load:
     Cookie named 'user' is not set! (Because cookies become available only in the next request).

Output after refreshing the page:
     Cookie user is set!
     Value is: John Smith

Important Notes:

(1) Cookies are only available in the next request, not the same request. After the first run, you refresh/reload the page in the browser. On the second request, PHP will receive the updated cookie from the browser.

(2) Remember that the setcookie() function must be used before the <html> tag because cookies are sent to the browser in the HTTP header, not in the body of the page.

(3) PHP always stores cookies as string values inside the $_COOKIE superglobal array.

(4) When you retrieve a cookie value, it is always returned as a string, regardless of how you originally set it (number, boolean, array, etc.).

(5) If you stored a numeric value as a cookie, you must cast it back ot its original type. Look at the example below.

<?php
setcookie("age", 25, time() + 3600, "/");
if (isset($_COOKIE["age"])) {
   echo $_COOKIE["age"]. "<br>"; // "25" (string)
   echo gettype($_COOKIE["age"]) . "<br>"; // string
   $age = (int) $_COOKIE["age"]; // Casting back to integer.
   echo gettype($age); // integer
}
?>
Output:
      25
      string 
      integer


(6) If you stored a serialized array or an object as a cookie value, you must deserialize or JSON decode it to get the original data type.

<?php
// Store array as JSON.
$colors = ["red", "green", "blue"];
setcookie("colors", json_encode($colors), time() + 3600, "/");

if (isset($_COOKIE["colors"])) {
    $cookieColors = json_decode($_COOKIE["colors"], true);
    print_r($cookieColors);
}
?>
Output:
      Array ( [0] => red [1] => green [2] => blue )

How to Modify a Cookie Value in PHP?


To modify a cookie in PHP, again set the cookie using the setcookie() function. Look at the below example code.

Example: Modifying a Cookie Value

<?php
$cookie_name = "user";
$cookie_value = "John Smith";
setcookie($cookie_name, $cookie_value, time() + 3600, "/");

// Update the cookie value.
setcookie("user", "John David", time() + 3600, "/");
echo "Cookie has been updated!" . "<br>";
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
     echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
     echo "Cookie '" . $cookie_name . "' is set!<br>";
     echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Output:
       Cookie has been updated!
       Cookie 'user' is set!
       Value is: John David

Cookies are available only in the next request. If you want to see the updated value immediately, assign it to $_COOKIE manually in your code.

// Manually update $_COOKIE for the current request.
$_COOKIE["user"] = "David";

How to Delete a Cookie in PHP?


To delete a cookie, use the setcookie() function with an expiration time in the past value.

Example: Deleting a Cookie

<?php
// Set the expiration time to one hour ago.
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Output:
      Cookie 'user' is deleted.

Setting Multiple Cookies in PHP


In PHP, you can set more than one cookie for the same user. Each cookie must have a unique name, otherwise, the latest one will overwrite the previous cookie. You create multiple cookies by calling the setcookie() function multiple times with different names.

Example 1: Setting Multiple Cookies

<?php
// Setting multiple cookies
setcookie("user", "John", time() + 3600, "/"); // Cookie 1
setcookie("email", "john@gmail.com", time() + 3600, "/"); // Cookie 2
setcookie("language", "English", time() + 3600, "/"); // Cookie 3

echo "Multiple cookies have been set successfully!";
?>

In this example, the cookie named “user” stores the username “John”. The cookie named “email” stores the email address. Similarly, the “language” cookie stores the user’s preferred language. All cookies will expire in 1 hour and are available across the entire website (/).

Example 2: Reading Multiple Cookies

Once cookies have been set, you can read them using the $_COOKIE superglobal array.

<?php
if(isset($_COOKIE["user"])) {
    echo "User: " . $_COOKIE["user"] . "<br>";
}
if(isset($_COOKIE["email"])) {
    echo "Email: " . $_COOKIE["email"] . "<br>";
}
if(isset($_COOKIE["language"])) {
    echo "Language: " . $_COOKIE["language"] . "<br>";
}
?>
Output (after refreshing the page):
     User: John
     Email: john@gmail.com
     Language: English

Example 3: Setting Cookies with Different Expiry Times

You can also set multiple cookies with different expiry times. Look at the below example code.

<?php
setcookie("user", "Saanvi", time() + 3600, "/"); // 1 hour
setcookie("theme", "dark", time() + (86400 * 7), "/"); // 7 days
setcookie("country", "India", time() + (86400 * 30), "/"); // 30 days
?>

Secure Cookies in PHP (HTTPS & HttpOnly)


When you are dealing with sensitive information like authentication tokens, session IDs, or user credentials, it’s very important to protect cookies from being stolen or misused.

PHP allows you to make cookies more secure by using two important flags:

  • secure flag
  • httponly flag

1. Secure Flag (secure = true)

When you set the secure flag, the cookie will only be sent over HTTPS connections. This prevents attackers from intercepting the cookie in plain-text HTTP requests. If the connection is not HTTPS, the cookie will not be sent.

2. HttpOnly Flag (httponly = true)

When you set the HttpOnly flag, the JavaScript (document.cookie) cannot access the cookie. This prevents attackers from stealing cookies using Cross-Site Scripting (XSS) attacks. The cookie will only be accessible by the server via PHP.

Example: Secure Cookie

<?php
// Set a secure cookie for login token.
setcookie(
     "login_token",
     "abc123xyz",
      time() + 3600, // Expires in 1 hour.
     "/", // Available across the whole domain.
     "scientecheasy.com", // Domain
      true, // Secure = true (only over HTTPS)
      true // HttpOnly = true (not accessible via JS)
);
echo "Secure cookie has been set!";
?>

In the example, secure = true ensures that the cookie will only be transmitted if the site is accessed over HTTPS. Meanwhile, httponly = true ensures that the cookie cannot be accessed or stolen via JavaScript (using document.cookie).

For maximum protection, especially when you are dealing with logins, sessions, or tokens, you should always use both secure and httponly together.