PHP Cookies
Understanding Cookies in PHP
A cookie is a small text file stored on a user's computer by a web server. It helps identify returning visitors and maintain user-specific data. When a browser requests a page, it sends all relevant cookies back to the server. PHP provides powerful functions to create, read, update, and delete cookies easily.
How to Create Cookies in PHP
Use the setcookie()
function to create cookies:
setcookie(name, value, expire, path, domain, secure, httponly);
- Only the
name
parameter is required -
The
expire
parameter sets when the cookie will be automatically deleted
Example: Setting a Cookie
<?php
$cookieName = "username";
$cookieValue = "JohnDoe123";
$expiryTime = time() + (86400 * 30); // Expires in 30 days
setcookie($cookieName, $cookieValue, $expiryTime, "/");
?>
Retrieving Cookie Values
Access cookies using the $_COOKIE
superglobal array:
<?php
if(isset($_COOKIE[$cookieName])) {
echo "Welcome back, " . $_COOKIE[$cookieName] . "!";
} else {
echo "Cookie not set!";
}
?>
Updating PHP Cookies
Modify a cookie by setting it again with new values:
<?php
setcookie("username", "NewUsername123", time() + (86400 * 30), "/");
?>
Deleting Cookies in PHP
To remove a cookie, set its expiration to a past time:
<?php
setcookie("username", "", time() - 3600, "/"); // Expire 1 hour ago
echo "Cookie deleted successfully!";
?>
Checking if Cookies Are Enabled
Test browser cookie support with this simple script:
<?php
setcookie("test_cookie", "check", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled!";
} else {
echo "Please enable cookies for best experience.";
}
?>
</body>
</html>
Best Practices for PHP Cookies
- Always set cookies before any HTML output
- Use
secure
flag for HTTPS sites - Consider
httponly
flag for security - Store minimal, non-sensitive data
PHP Cookie Frequently Asked Questions
-
❓ What PHP function creates cookies?
✅setcookie()
-
❓ How long do PHP cookies last?
✅ Until their expiration time (or until browser clears them) -
❔ Are cookies secure?
✅ When properly configured withSecure
andHttpOnly
flags
Complete Cookie Example
<?php
// Set cookie parameters
$cookieName = "user_preferences";
$cookieValue = json_encode(["theme" => "dark", "language" => "en"]);
$expiryTime = time() + (86400 * 30); // 30 days
$path = "/";
$domain = $_SERVER['HTTP_HOST'];
$secure = true; // Only send over HTTPS
$httponly = true; // Prevent JavaScript access
// Set the cookie
setcookie($cookieName, $cookieValue, $expiryTime, $path, $domain, $secure, $httponly);
// Check if cookie exists
if(isset($_COOKIE[$cookieName])) {
$preferences = json_decode($_COOKIE[$cookieName], true);
echo "Current theme: " . htmlspecialchars($preferences['theme']);
} else {
echo "Setting your preferences...";
}
// Delete cookie example
if(isset($_GET['logout'])) {
setcookie($cookieName, "", time() - 3600, $path, $domain, $secure, $httponly);
echo "Preferences cleared!";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<h1>Cookie Management</h1>
<a href="?logout=1">Clear Preferences</a>
</body>
</html>