PHP Cookies

Cookies are small files stored on the client’s computer that are used to remember information about the user. In PHP, you can set and retrieve cookies using the setcookie() function.

Setting a Cookie

<?php
setcookie("user", "John Doe", time() + (86400 * 30), "/"); // 86400 = 1 day
?>

Explanation: This example sets a cookie named user with the value John Doe. The cookie will expire in 30 days.

Retrieving a Cookie

<?php
if(isset($_COOKIE["user"])) {
    echo ":User  " . $_COOKIE["user"];
} else {
    echo "User  cookie is not set.";
}
?>

Explanation: This example checks if the user cookie is set and retrieves its value. If the cookie is not set, it displays a message indicating that the cookie is not set.

Deleting a Cookie

<?php
setcookie("user", "", time() - 3600, "/"); // Delete the cookie by setting its expiration time in the past
?>

Explanation: This example deletes the user cookie by setting its expiration time to a point in the past.