PHP Cookies Tutorial

Welcome to The Coding College! In this tutorial, we’ll cover everything you need to know about PHP Cookies. Cookies are small pieces of data stored on the client’s browser, and they are essential for managing state, storing preferences, and tracking user behavior in web applications.

What are Cookies?

Cookies are small text files stored on a user’s device by a web server via a browser. They allow web applications to:

  • Store user data (e.g., preferences, session IDs).
  • Track user activity across pages or visits.
  • Maintain login sessions.

How Cookies Work in PHP

  1. Set a Cookie: Use the setcookie() function to create a cookie and send it to the browser.
  2. Access a Cookie: Read cookie data from the $_COOKIE superglobal.
  3. Delete a Cookie: Set the cookie with an expired timestamp.

Setting a Cookie in PHP

The setcookie() function is used to create cookies.

Syntax

setcookie(name, value, expire, path, domain, secure, httponly);

Parameters:

  • name: The name of the cookie.
  • value: The value stored in the cookie.
  • expire: Expiration time (in seconds from the current time).
  • path: Directory scope of the cookie (default is /).
  • domain: Domain where the cookie is available (e.g., example.com).
  • secure: Boolean to allow cookies only over HTTPS.
  • httponly: Boolean to allow access only via HTTP (not JavaScript).

Example: Setting a Cookie

<?php
// Set a cookie named "user" with value "John Doe" that expires in 1 day
setcookie("user", "John Doe", time() + (86400 * 1), "/"); // 86400 seconds = 1 day
echo "Cookie 'user' is set!";
?>

Accessing Cookies in PHP

Cookies can be accessed using the $_COOKIE superglobal.

Example: Accessing a Cookie

<?php
if (isset($_COOKIE["user"])) {
    echo "Welcome back, " . $_COOKIE["user"] . "!";
} else {
    echo "Welcome, new user!";
}
?>

Updating a Cookie in PHP

To update a cookie, simply use the setcookie() function again with the same name but a new value.

Example: Updating a Cookie

<?php
setcookie("user", "Jane Doe", time() + (86400 * 1), "/");
echo "Cookie 'user' has been updated!";
?>

Deleting a Cookie in PHP

To delete a cookie, set its expiration time to a past timestamp using time() - 3600.

Example: Deleting a Cookie

<?php
setcookie("user", "", time() - 3600, "/"); // Expire the cookie
echo "Cookie 'user' has been deleted.";
?>

Cookie Best Practices

1. Set Expiration Dates

Always set an appropriate expiration time for cookies to manage user sessions effectively.

2. Use Secure and HTTPOnly Flags

  • secure: Ensures cookies are sent only over HTTPS.
  • httponly: Prevents cookies from being accessed by JavaScript, improving security against XSS attacks.

Example: Secure and HTTPOnly Cookies

<?php
setcookie("secureCookie", "Secure Value", time() + 3600, "/", "", true, true);
?>

3. Limit Domain and Path

Restrict the domain and path to prevent unnecessary exposure.

4. Avoid Storing Sensitive Data

Never store sensitive information like passwords in cookies. Use session management instead.

Practical Examples of Cookies

Example 1: Remember User Preferences

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $theme = $_POST["theme"];
    setcookie("theme", $theme, time() + (86400 * 30), "/"); // Store theme preference for 30 days
    echo "Your theme preference has been saved!";
}

if (isset($_COOKIE["theme"])) {
    echo "Your preferred theme is: " . $_COOKIE["theme"];
} else {
    echo "No theme preference set.";
}
?>

HTML Form:

<form method="post">
    <label for="theme">Choose a theme:</label>
    <select name="theme" id="theme">
        <option value="light">Light</option>
        <option value="dark">Dark</option>
    </select>
    <button type="submit">Save Preference</button>
</form>

Example 2: Track User Visits

<?php
if (isset($_COOKIE["visitCount"])) {
    $visitCount = $_COOKIE["visitCount"] + 1;
} else {
    $visitCount = 1;
}

setcookie("visitCount", $visitCount, time() + (86400 * 30), "/");

echo "You have visited this site $visitCount times.";
?>

Example 3: Logout Using Cookies

<?php
if (isset($_COOKIE["user"])) {
    setcookie("user", "", time() - 3600, "/");
    echo "You have been logged out.";
} else {
    echo "No active session found.";
}
?>

Conclusion

Cookies are a powerful way to store user data and preferences on the client’s browser. In this tutorial, we covered:

  • How to set, access, update, and delete cookies.
  • Best practices for secure cookie usage.
  • Practical examples for real-world scenarios.

By leveraging cookies, you can enhance the user experience on your website. Explore more PHP tutorials at The Coding College to expand your programming skills. Happy coding! 🚀

Leave a Comment