← Back to PHP Course | Chapter 12: Sessions & Cookies | Lesson 3 of 5

PHP Cookies Introduction

What is a Cookie?

A cookie is a small piece of data the server asks the browser to store and send back on every later request to that site, commonly used to remember preferences or recognize a returning visitor without requiring login.

Example: What is a Cookie?

php
<?php
setcookie("theme", "dark");
echo "Cookie 'theme' will be sent back on the next request";
?>

Setting Cookie Expiration Dates

Cookies are deleted automatically when the browser closes unless you set an explicit expiration timestamp with setcookie(), which is what makes a 'remember me' checkbox actually persist across sessions.

Example: Setting Cookie Expiration Dates

php
<?php
setcookie("remember_me", "yes", time() + (86400 * 30));
echo "Cookie set to persist for 30 days";
?>

Configuring Cookie Paths and Domains

The path and domain parameters of a cookie control exactly which URLs on your server can read it back, letting you scope a cookie to one subfolder or share it across subdomains as needed.

Example: Configuring Cookie Paths and Domains

php
<?php
setcookie("cart", "abc123", 0, "/shop/");
echo "Cookie scoped to the /shop/ path only";
?>

Secure and HttpOnly Cookies

The Secure and HttpOnly flags harden a cookie against common attacks: Secure ensures it's only ever sent over HTTPS, and HttpOnly blocks JavaScript from reading it, which closes off a common XSS attack vector.

Example: Secure and HttpOnly Cookies

php
<?php
setcookie("session_token", "xyz", 0, "/", "", true, true);
echo "Secure: HTTPS only. HttpOnly: hidden from JavaScript.";
?>

Deleting Cookies

Because there's no direct delete operation, removing a cookie means calling setcookie() again with the same name but an expiration time in the past, telling the browser to discard it immediately.

Example: Deleting Cookies

php
<?php
setcookie("theme", "", time() - 3600);
echo "Cookie set to expire in the past -- browser will discard it";
?>
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.