PHP Cookies Introduction
In this page:
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
setcookie("theme", "dark");
echo "Cookie 'theme' will be sent back on the next request";
?>
Login to try C/C++/Java/PHP code in the editor
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
setcookie("remember_me", "yes", time() + (86400 * 30));
echo "Cookie set to persist for 30 days";
?>
Login to try C/C++/Java/PHP code in the editor
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
setcookie("cart", "abc123", 0, "/shop/");
echo "Cookie scoped to the /shop/ path only";
?>
Login to try C/C++/Java/PHP code in the editor
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
setcookie("session_token", "xyz", 0, "/", "", true, true);
echo "Secure: HTTPS only. HttpOnly: hidden from JavaScript.";
?>
Login to try C/C++/Java/PHP code in the editor
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
setcookie("theme", "", time() - 3600);
echo "Cookie set to expire in the past -- browser will discard it";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: