Professional Documents
Culture Documents
• They are typically used to store information about the user or their interactions with
a website
• Cookies are sent with each HTTP request, allowing the server to recognize the user
Creating a Cookie
// Syntax to set a cookie
setcookie(name, value, expiration, path, domain, secure, httponly);
$username = $_COOKIE["username"];
echo "Welcome, $username!";
<?php
$cookie_name = "username";
$cookie_value = "xyz";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Updating Cookie
• To update a cookie, simply set it again with the new value
// Updating a cookie
setcookie("username", "abc", time() + 3600, "/");
Deleteing Cookie
• To delete a cookie, set its expiration time to a past date
// Deleting a cookie
setcookie("username", "", time() - 3600, "/");
Security Considerations
• Be cautious about storing sensitive information in cookies
• Set the secure flag for sensitive cookies to ensure they are transmitted over HTTPS
• Use the httponly flag to prevent JavaScript access to sensitive cookies
• Always validate and sanitize cookie data to prevent security vulnerabilities
?