Cookies are small pieces of data stored on the client's computer by websites. In PHP, they're crucial for maintaining user information across multiple pages or visits.
Use the setcookie()
function to create a cookie. It should be called before any HTML output.
setcookie("user", "John Doe", time() + 3600, "/");
This creates a cookie named "user" with the value "John Doe", expiring in one hour, accessible across the entire website.
Access cookie values using the $_COOKIE
superglobal array:
if(isset($_COOKIE["user"])) {
echo "Welcome back, " . $_COOKIE["user"];
} else {
echo "Welcome, guest!";
}
To modify a cookie, simply set it again with a new value. To delete a cookie, set its expiration time to the past:
// Modify
setcookie("user", "Jane Doe", time() + 3600, "/");
// Delete
setcookie("user", "", time() - 3600, "/");
Cookies are often used for:
While cookies are useful, they can pose security risks if not handled properly. Always validate and sanitize cookie data, especially when used in database queries or output to prevent Cross-Site Scripting (XSS) attacks.
Remember: Cookies are stored on the client-side and can be manipulated. Never trust cookie data for critical operations without server-side verification.
PHP cookies provide a simple yet powerful way to store small amounts of data on the client-side. When used correctly, they enhance user experience and enable personalization across web sessions. However, always prioritize security and consider alternatives like sessions for sensitive data.