What is Cookie in PHP: Simple Explanation and Example
cookie in PHP is a small piece of data stored on the user's browser by a website to remember information between page visits. PHP uses the setcookie() function to create cookies that help track user preferences or login status.How It Works
Think of a cookie like a sticky note that a website leaves on your browser. When you visit a website, it can write a small note (the cookie) with some information, like your name or settings. The next time you visit, your browser shows that note back to the website, so it remembers you.
In PHP, the server sends this note using the setcookie() function before any page content is sent. The browser saves the cookie and sends it back with every request to the same website. This way, PHP can read the cookie and personalize your experience.
Example
This example shows how to set a cookie named user with the value John that lasts for one hour. It also shows how to read and display the cookie value.
<?php // Set a cookie named 'user' with value 'John' that expires in 1 hour setcookie('user', 'John', time() + 3600); // Check if the cookie is set and display it if (isset($_COOKIE['user'])) { echo 'Hello, ' . $_COOKIE['user'] . '!'; } else { echo 'Cookie is not set.'; } ?>
When to Use
Cookies are useful when you want to remember information about a user between visits without needing them to log in every time. For example, you can use cookies to:
- Keep users logged in on a website
- Save user preferences like language or theme
- Track user behavior for analytics
However, cookies should not be used to store sensitive data because they are stored on the user's device and can be accessed or modified.
Key Points
- Cookies store small pieces of data on the user's browser.
- PHP uses
setcookie()to create cookies before output. - Cookies help remember users and preferences between visits.
- Cookies have expiration times and can be deleted by the user.
- Do not store sensitive information in cookies.