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.
Setting a Cookie in PHP
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);- name: The name of the cookie.
- value: The value stored in the cookie.
- expire: The time the cookie expires (Unix timestamp).
- path: The path on the server where the cookie is
available. Use
/for the entire domain. - domain: The domain that the cookie is available to.
- secure: If
true, the cookie is only transmitted over secure HTTPS connections. - httponly: If
true, the cookie is inaccessible to client-side scripts (like JavaScript), helping prevent XSS attacks.
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, "/");
?>Retrieving a Cookie in PHP
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!";
}
?>Modifying a Cookie
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, "/");
?>Deleting a Cookie
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, "/");
?>