PHP Cookie Handling

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!";
?>

Try It Now

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!";
}
?>

Try It Now

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.";
?>

Try It Now


๐ŸŽฏ 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? ๐Ÿค”