You are on page 1of 11

PHP Cookie Management

Understanding and Implementing Cookies in PHP


Topics to be covered...
• Introduction
• Creating Cookies
• Retrieving Cookies
• Updating Cookies
• Deleting Cookies
• Using Cookies for Session Management
• Security Considerations
Introduction to Cookies
• Cookies are small pieces of data that a web server sends to a user's web browser
for storage

• 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);

• name: The name of the cookie.


• value: The value of the cookie.
• expiration: The expiration time of the cookie (in seconds).
• path (optional): The path on the server where the cookie is available.
• domain (optional): The domain for which the cookie is valid.
• secure (optional): If true, the cookie will only be sent over HTTPS.
• httponly (optional): If true, the cookie can only be accessed through HTTP, not JavaScript.
Creating Cookie
• Example

// Setting a cookie that expires in 1 hour


setcookie("username", "xyz", time() + 3600, "/");
Retrieving Cookie
• Cookies can be accessed using the $_COOKIE superglobal

// Retrieving a cookie value

$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
?

You might also like