PHP Cookie Handling – Storing User Data in the Browser ๐ช
Ever noticed how a website “remembers” you? Thatโs cookies at work! ๐ช Cookies allow websites to store small pieces of data in a user’s browser, like usernames, preferences, or even shopping cart items.
๐น What is a Cookie?
A cookie is a small text file stored on the user’s computer by their web browser. In PHP, you can set cookies using the setcookie()
function.
๐ Example: Setting a Cookie
The following example sets a cookie named user
that expires in 1 hour.
<?php // Set a cookie setcookie("user", "JohnDoe", time() + 3600, "/"); echo "Cookie has been set!"; ?>
Explanation:
"user"
โ Cookie name."JohnDoe"
โ Cookie value.time() + 3600
โ Expires in 1 hour."/"
โ Available across the entire website.
๐น Retrieving a Cookie
Once a cookie is set, you can access it using the $_COOKIE
superglobal.
๐ Example: Getting a Cookie Value
<?php if(isset($_COOKIE["user"])) { echo "Welcome back, " . $_COOKIE["user"] . "!"; } else { echo "No cookie found!"; } ?>
Output: Welcome back, JohnDoe! (if the cookie exists)
๐น Deleting a Cookie
To delete a cookie, set its expiration time to a past timestamp.
๐ Example: Deleting a Cookie
<?php // Delete a cookie by setting its expiration to the past setcookie("user", "", time() - 3600, "/"); echo "Cookie has been deleted."; ?>
๐ฏ Key Takeaways
setcookie(name, value, expire, path)
โ Creates a cookie.$_COOKIE["name"]
โ Retrieves a cookie.setcookie(name, "", time() - 3600)
โ Deletes a cookie.
๐ Practice Time!
Try setting a cookie for user preferences, like theme color ๐จ or language ๐. How would you use cookies to store a “Remember Me” login? ๐ค