PHP Cookies: Complete Guide to Setting, Retrieving & Managing Cookies in PHP
Last updated 3 months, 4 weeks ago | 105 views 75 5

Introduction: Why Cookies Matter in PHP Development
Cookies are a foundational part of modern web applications. Whether you're storing user preferences, managing authentication, or enabling session continuity, cookies are a simple and efficient solution. In PHP, cookies allow you to store small pieces of data on the client's browser, which persist across page reloads and browser sessions.
In this article, you’ll learn everything you need to create, read, and delete cookies in PHP—plus how to handle them securely and efficiently.
What Are Cookies?
A cookie is a small text file stored in the user's browser. It contains data that the server can read during future requests. PHP handles cookies through the global $_COOKIE
array and the setcookie()
function.
Setting a Cookie in PHP
Use setcookie()
to send a cookie to the user's browser. This must be called before any output is sent to the browser.
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
Example:
<?php
// Set a cookie that expires in 1 hour
setcookie("username", "JohnDoe", time() + 3600, "/");
?>
Explanation:
-
"username"
→ Cookie name -
"JohnDoe"
→ Cookie value -
time() + 3600
→ Expiration time (current time + 3600 seconds) -
"/"
→ Available across the entire domain
Retrieving a Cookie in PHP
You can access a cookie's value using the $_COOKIE
superglobal.
Example:
<?php
if (isset($_COOKIE["username"])) {
echo "Welcome, " . $_COOKIE["username"];
} else {
echo "User not recognized.";
}
?>
Deleting a Cookie in PHP
To delete a cookie, set its expiration time to a time in the past.
Example:
<?php
// Delete the cookie by setting its expiration time to the past
setcookie("username", "", time() - 3600, "/");
?>
Complete Functional Example
Here’s a simple PHP app with three pages: one to set, one to retrieve, and one to delete a cookie.
set_cookie.php
<?php
setcookie("theme", "dark", time() + 86400, "/"); // 1 day
echo "Cookie has been set.";
?>
get_cookie.php
<?php
if (isset($_COOKIE["theme"])) {
echo "Selected Theme: " . $_COOKIE["theme"];
} else {
echo "No theme selected.";
}
?>
delete_cookie.php
<?php
setcookie("theme", "", time() - 3600, "/");
echo "Cookie deleted.";
?>
⚠️ Tips & Common Pitfalls
✅ Best Practices
-
Always call
setcookie()
before any HTML output. -
Set
httponly
totrue
to prevent JavaScript access. -
Use the
secure
flag for HTTPS-only cookies. -
Validate cookie data before using it in logic or output.
❌ Common Mistakes
-
Outputting content (like echo or HTML) before
setcookie()
. -
Forgetting to set the path can limit cookie availability.
-
Not checking if a cookie exists before accessing it.
Cookie Function Comparison Table
Function | Purpose | Usage Example |
---|---|---|
setcookie() |
Set or update a cookie | setcookie("user", "john", time()+3600); |
$_COOKIE |
Retrieve cookie value | $_COOKIE["user"] |
setcookie() |
Delete cookie (expire it) | setcookie("user", "", time()-3600); |
Security Considerations for PHP Cookies
Option | Description | Benefit |
---|---|---|
secure |
Sends cookie over HTTPS only | Prevents man-in-the-middle |
httponly |
Disallows JavaScript access | Blocks XSS attacks |
samesite |
Controls cookie sharing across sites | Prevents CSRF attacks |
// Example with all flags
setcookie("authToken", "abc123", time() + 3600, "/", "", true, true);
Use Cases of PHP Cookies
-
Storing user preferences (e.g., dark/light mode)
-
Tracking logged-in sessions
-
Remembering items in a shopping cart
-
Saving language or region settings
Conclusion: Mastering Cookies in PHP
Cookies are a powerful tool in your PHP development arsenal. From simple personalization to session control, they help maintain a smooth, user-friendly experience.
✅ Quick Takeaways:
-
Use
setcookie()
carefully and before output. -
Sanitize and validate all cookie input.
-
Use security flags like
httponly
,secure
, andsamesite
.
With proper implementation, PHP cookies are lightweight and extremely useful in building interactive, stateful web applications.