What Are Cookies in PHP – Store & Retrieve Data
Cookies are small pieces of data stored on the user’s browser. They are used to remember information about the user, such as preferences or login status, across multiple pages or even after the user closes the browser.
Key Features of Cookies
- Stored in the Browser: Cookies are saved on the client-side, allowing data to persist between visits.
- Key-Value Pairs: Cookies store data as key-value pairs.
- Expiration: Cookies can have a set expiration time, after which they are deleted.
- Limited Size: Cookies have a size limit (typically 4KB per cookie).
How Cookies Work
- A server sends a cookie to the user’s browser using the
Set-Cookie
header. - The browser stores the cookie and sends it back to the server with each subsequent request.
- The server uses the cookie to identify the user or retrieve stored information.
Using Cookies in PHP
1. Setting a Cookie
To create a cookie in PHP, use the setcookie()
function. This function must be called before any output is sent to the browser.
<?php setcookie("username", "JohnDoe", time() + 3600, "/"); // Expires in 1 hour echo "Cookie 'username' is set!"; ?>
Parameters:
"username"
: The name of the cookie."JohnDoe"
: The value of the cookie.time() + 3600
: Expiration time (current time + 3600 seconds = 1 hour)."/"
: Path where the cookie is accessible (e.g., entire site or specific directory).
2. Accessing Cookies
To retrieve the value of a cookie, use the $_COOKIE
superglobal array.
<?php if (isset($_COOKIE['username'])) { echo "Welcome, " . $_COOKIE['username']; } else { echo "No cookie found."; } ?>
3. Updating a Cookie
To update a cookie, call setcookie()
with the same name and a new value.
<?php setcookie("username", "JaneDoe", time() + 3600, "/"); // Update value echo "Cookie 'username' updated!"; ?>
4. Deleting a Cookie
To delete a cookie, set its expiration time to a past date.
<?php setcookie("username", "", time() - 3600, "/"); // Delete cookie echo "Cookie 'username' deleted."; ?>
Common Use Cases for Cookies
- Remembering User Preferences:
setcookie("theme", "dark", time() + (86400 * 30), "/"); // Store theme for 30 days
- User Authentication:
setcookie("user_id", "12345", time() + 3600, "/"); // Keep user logged in for 1 hour
- Tracking User Activity:
setcookie("last_visited", date("Y-m-d H:i:s"), time() + (86400 * 7), "/"); // Store last visit date
Cookies vs. Sessions
Feature | Cookies | Sessions |
---|---|---|
Storage Location | Client-side (browser) | Server-side |
Size Limit | 4KB per cookie | No size limit (depends on server) |
Lifespan | Can persist after browser closes | Ends when the session expires |
Security | Less secure | More secure |
Best Practices for Cookies
- Use HTTPS: Set the
secure
flag to ensure cookies are sent over encrypted connections.setcookie("username", "JohnDoe", time() + 3600, "/", "", true); // Secure cookie
- Use
httponly
: Prevent JavaScript from accessing cookies.setcookie("username", "JohnDoe", time() + 3600, "/", "", true, true);
- Avoid Storing Sensitive Data: Use sessions or database storage for sensitive information.
- Set Expiry Wisely: Only use long expiration times when necessary.
Cookies are a simple and effective way to remember user information and enhance user experiences across web applications. However, they should be used responsibly, keeping security and privacy in mind.