☜
☞
cookies
Cookies in PHP are a way to store small amounts of data on the client side, which can be used to track user activity or remember user preferences. Below is an example of how to set, retrieve, and delete cookies in PHP.
Setting a Cookie
To set a cookie in PHP, use the setcookie() function. Here's an example of setting a cookie:
<?php
// Set a cookie
$cookie_name = "user";
$cookie_value = "John Doe";
$cookie_expiry = time() + (86400 * 30); // 86400 = 1 day, so the cookie will expire in 30 days
setcookie($cookie_name, $cookie_value, $cookie_expiry, "/"); // "/" means the cookie is available in the entire domain
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Cookie</title>
</head>
<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>
Retrieving a Cookie
To retrieve a cookie in PHP, you use the $_COOKIE superglobal array. Here’s an example:
<?php
// Retrieve the cookie
$cookie_name = "user";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Retrieve Cookie</title>
</head>
<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>
Deleting a Cookie
To delete a cookie, you set its expiration date to a past time. Here’s an example:
<?php
// Delete a cookie
$cookie_name = "user";
setcookie($cookie_name, "", time() - 3600, "/"); // set the expiration date to one hour ago
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Delete Cookie</title>
</head>
<body>
<?php
echo "Cookie '" . $cookie_name . "' is deleted.";
?>
</body>
</html>
Explanation
Setting a Cookie:
- setcookie(name, value, expire, path): Sets a cookie.
- time() + (86400 * 30): Sets the cookie to expire in 30 days (86400 seconds in a day).
- "/": The cookie is available within the entire domain.
Retrieving a Cookie:
- $_COOKIE['name']: Retrieves the value of the cookie.
Deleting a Cookie:
- setcookie(name, "", time() - 3600, "/"): Sets the cookie’s expiration date to one hour ago, effectively deleting it.
These examples show the basic operations of setting, retrieving, and deleting cookies in PHP. Place these scripts in your web server directory and access them through your browser to see the results.
☜
☞