PHP Cookies
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.
1. Create Cookies with setcookie()
A cookie is created with the setcookie() function. It must appear before the <html> tag.
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
// Cookie expires in 30 days (86400 * 30)
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
2. Retrieve a Cookie Value
To access a cookie, we use the PHP global variable $_COOKIE. We should also use isset() to check if the cookie is set.
<?php
if(!isset($_COOKIE["user"])) {
echo "Cookie named 'user' is not set!";
} else {
echo "Cookie 'user' is set!<br>";
echo "Value is: " . $_COOKIE["user"];
}
?>
3. Modify a Cookie Value
To modify a cookie, just set the cookie again using the setcookie() function with the same name, but a different value.
4. Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past (e.g., minus one hour).
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
5. Check if Cookies are Enabled
You can check if the user's browser has cookies enabled by trying to set a test cookie and then counting the $_COOKIE array.
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
Security Tip: Cookies can be manipulated by users. Never store sensitive data like passwords or bank details in a cookie. Use Sessions for sensitive information instead.