PHP Cookie Management
In this page:
Introduction to Cookies
setcookie() is the function that actually creates a cookie on the visitor's machine; it takes the cookie's name and value plus optional settings that control its lifetime, scope, and security.
Example: Introduction to Cookies
<?php
setcookie("username", "Alice");
echo "Cookie created with a name and value";
?>
Login to try C/C++/Java/PHP code in the editor
Setting Cookie Expiration
If you don't pass an expiration time to setcookie(), the cookie is treated as a session cookie and disappears the moment the browser closes -- explicitly setting a future timestamp is what makes data persist across visits.
Example: Setting Cookie Expiration
<?php
setcookie("username", "Alice"); // session cookie -- disappears when browser closes
setcookie("remembered_user", "Alice", time() + 86400); // persists for 1 day
echo "Two cookies set with different lifetimes";
?>
Login to try C/C++/Java/PHP code in the editor
Cookie Security Options
Marking a cookie HttpOnly stops client-side scripts from reading it (blocking a common XSS attack path), while marking it Secure ensures the browser only ever transmits it over an encrypted HTTPS connection.
Example: Cookie Security Options
<?php
setcookie("token", "abc123", ['httponly' => true, 'secure' => true]);
echo "HttpOnly blocks JS access; Secure requires HTTPS";
?>
Login to try C/C++/Java/PHP code in the editor
Deleting Cookies
Setting a cookie's expiration to a timestamp in the past is the standard way to delete it, since there's no dedicated delete function -- the browser sees the expired date and discards the cookie on its next check.
Example: Deleting Cookies
<?php
setcookie("username", "", time() - 3600);
echo "Expiration set in the past -- cookie will be discarded";
?>
Login to try C/C++/Java/PHP code in the editor
Checking if Cookies are Enabled
You can test cookie support by setting a throwaway cookie on one page load and checking for its presence on the next; if it's missing, the visitor's browser likely has cookies disabled or blocked.
Example: Checking if Cookies are Enabled
<?php
setcookie("test_cookie", "1");
if (isset($_COOKIE['test_cookie'])) {
echo "Cookies are enabled";
} else {
echo "Cookies may be disabled -- check on next page load";
}
?>
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: