Cookies are small files that are stored on the user's computer. PHP allows you to set, retrieve, and delete cookies.
To set a cookie in PHP, use the setcookie()
function:
<?php
setcookie("username", "JohnDoe", time() + 3600); // Cookie expires in 1 hour
echo "Cookie set!";
?>
To access the value of a cookie, use the $_COOKIE
superglobal:
<?php
if(isset($_COOKIE['username'])) {
echo "Hello, " . $_COOKIE['username'];
} else {
echo "Cookie not set.";
}
?>
To delete a cookie, set its expiration time to a past time:
<?php
setcookie("username", "", time() - 3600); // Delete the cookie
echo "Cookie deleted!";
?>
Set a cookie with your name and display it on a new page.
Answers: Use setcookie()
to set a cookie. Access cookies using the $_COOKIE
superglobal.