Cookies in PHP are used to store small pieces of data on the client's computer. They are commonly used for sessions, personalization, tracking, and more. Here's a guide on how to work with cookies in PHP:
You can set a cookie using the setcookie() function. It takes several parameters, but the most commonly used ones are the name, value, expiration time, and path.
// Set a cookie named "user" with value "John Doe"
setcookie("user", "John Doe", time() + 3600, "/"); // Expires in 1 hour, available on the entire domain
You can retrieve cookie values using the $_COOKIE superglobal.
// Check if the "user" cookie is set
if(isset($_COOKIE["user"])) {
echo "Welcome " . $_COOKIE["user"] . "!";
} else {
echo "Cookie not set!";
}
To modify a cookie, you can set a new cookie with the same name.
// Modify the "user" cookie's value
setcookie("user", "Jane Smith", time() + 3600, "/");
To delete a cookie, set its expiration time to a past value.
// Delete the "user" cookie
setcookie("user", "", time() - 3600, "/");
Example:
Here's a simple example that sets, retrieves, modifies, and deletes a cookie:
// Set a cookie
setcookie("user", "John Doe", time() + 3600, "/");
// Retrieve and display the cookie
if(isset($_COOKIE["user"])) {
echo "Welcome " . $_COOKIE["user"] . "!";
} else {
echo "Cookie not set!";
}
// Modify the cookie
setcookie("user", "Jane Smith", time() + 3600, "/");
// Delete the cookie
setcookie("user", "", time() - 3600, "/");
echo "Cookie deleted.";
If you omit the expiration time, the cookie becomes a session cookie, which is deleted when the browser is closed.
// Set a session cookie
setcookie("session_cookie", "value"); // Expires when the browser is closed
Cookies are a convenient way to store small amounts of data on the client's computer, but remember not to store sensitive information in cookies as they are stored on the client side and can be manipulated.