Cookies help websites remember you by saving small pieces of information on your computer. This way, the website can greet you or keep you logged in next time.
Setting and reading cookies in PHP
<?php // To set a cookie setcookie('name', 'value', expire, path, domain, secure, httponly); // To read a cookie $_COOKIE['name']; ?>
setcookie must be called before any HTML output.
Only the name and value are required; others are optional.
<?php setcookie('user', 'Alice'); ?>
<?php setcookie('user', 'Alice', time() + 3600); ?>
<?php if (isset($_COOKIE['user'])) { echo 'Hello, ' . $_COOKIE['user']; } else { echo 'Hello, guest!'; } ?>
This program sets a cookie called 'visitor' with the value 'John' that lasts for one day. Then it checks if the cookie exists and greets the visitor by name. If the cookie is not set yet, it welcomes a new visitor.
<?php // Set a cookie named 'visitor' with value 'John' that expires in 1 day setcookie('visitor', 'John', time() + 86400); // Check if the cookie is set and print a greeting if (isset($_COOKIE['visitor'])) { echo "Welcome back, " . $_COOKIE['visitor'] . "!"; } else { echo "Hello, new visitor!"; } ?>
Cookies are sent with the HTTP headers, so setcookie() must be called before any output.
Cookies are stored on the user's computer and can be deleted or blocked by the user.
Use isset() to check if a cookie exists before reading it to avoid errors.
Cookies store small data on the user's computer to remember information.
Use setcookie() to create cookies and $_COOKIE to read them.
Always check if a cookie exists before using its value.