PHP Cookies

PHP Cookies

A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.

Cookies are often used to identify users, store user preferences (like Dark Mode/Light Mode), or track visitor behavior for analytics.


Creating a Cookie

A cookie is created with the setcookie() function.

Syntax:

setcookie(name, value, expire, path, domain, secure, httponly);
Only the `name` parameter is required. All other parameters are optional.

Important: The setcookie() function must appear BEFORE the <html> tag. You cannot send a cookie after you have sent any HTML output to the browser!

Set Cookie Example

<?php
$cookie_name = "user";
$cookie_value = "John Doe";

// Set the cookie to expire in 30 days (86400 seconds = 1 day) setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); ?>

(Note: The "/" means the cookie is available across the entire website. If you set it to "/admin/", it will only be available in the admin directory).


Accessing a Cookie

Once a cookie has been set, it is automatically passed to the $_COOKIE superglobal array on subsequent page loads. You can retrieve its value easily!

Read Cookie Example

<?php
if(!isset($_COOKIE["user"])) {
  echo "Cookie named 'user' is not set!";
} else {
  echo "Cookie 'user' is set!<br>";
  echo "Value is: " . $_COOKIE["user"];
}
?>

Deleting a Cookie

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

// Set the expiration date to one hour ago
setcookie("user", "", time() - 3600);

Exercise

?

Where must the setcookie() function be placed in your PHP script?