How to Set and Retrieve a Cookie in PHP

This article provides a straightforward guide on how to set and retrieve cookies in PHP. You will learn the syntax for the setcookie() function, how to access stored cookie data using the $_COOKIE superglobal, and how to safely modify or delete cookies.

To set a cookie in PHP, use the built-in setcookie() function. This function must be executed before any HTML or output is sent to the browser because cookies are transmitted via HTTP headers.

Syntax

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

Example

The following code sets a cookie named “user” with the value “John Doe” that expires in one hour:

<?php
$cookie_name = "user";
$cookie_value = "John Doe";
$expiration_time = time() + 3600; // Current time + 3600 seconds (1 hour)

setcookie($cookie_name, $cookie_value, $expiration_time, "/");
?>

To retrieve a cookie, use the PHP global variable $_COOKIE. This is an associative array containing all cookie names and values sent by the browser.

Example

Before accessing a cookie, check if it exists using the isset() function to prevent undefined index warnings:

<?php
if (isset($_COOKIE["user"])) {
    echo "Welcome back, " . $_COOKIE["user"] . "!";
} else {
    echo "Welcome, guest!";
}
?>

To update a cookie’s value or expiration time, call the setcookie() function again using the same cookie name but with the new parameters.

<?php
// Updating the "user" cookie value and extending its expiration
setcookie("user", "Jane Doe", time() + 3600, "/");
?>

To delete a cookie, call setcookie() with the cookie’s name and set the expiration parameter to a time in the past.

<?php
// Deleting the "user" cookie by setting expiration to 1 hour ago
setcookie("user", "", time() - 3600, "/");
?>