Cookies help websites remember you. They store small bits of information on your computer so the site can recognize you later.
How cookies work in PHP
<?php setcookie(name, value, expires, path, domain, secure, httponly); ?>
name is the cookie's name.
value is the data stored in the cookie.
expires is the time the cookie expires (as a Unix timestamp).
Only name and value are required; others are optional.
<?php setcookie("user", "Alice"); ?>
<?php setcookie("theme", "dark", time() + 3600); ?>
<?php setcookie("session", "12345", time() + 86400, "/", "example.com", true, true); ?>
This program sets a cookie called 'visitor' with the value 'John' that lasts for one hour. Then it checks if the cookie exists and greets the visitor by name if it does. If not, it welcomes a new visitor.
<?php // Set a cookie named 'visitor' with value 'John' that expires in 1 hour setcookie("visitor", "John", time() + 3600); // Check if the cookie is set and print a message if (isset($_COOKIE["visitor"])) { echo "Welcome back, " . $_COOKIE["visitor"] . "!"; } else { echo "Hello, new visitor!"; } ?>
Cookies must be set before any HTML or output is sent to the browser.
Cookies are stored on the user's computer and can be deleted by the user anytime.
Cookies can only store strings, so complex data must be converted (e.g., using JSON).
Cookies store small data on the user's computer to remember information.
Use setcookie() in PHP to create cookies.
Cookies help improve user experience by saving preferences and login info.