HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP $_COOKIE

A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.


1. Setting a Cookie

A cookie is created with the setcookie() function. This function must appear before any HTML tags.

Syntax: setcookie(name, value, expire, path, domain, secure, httponly)

<?php
    $cookie_name = "user";
    $cookie_value = "John Doe";
    // Set cookie to expire in 30 days (86400 * 30)
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); 
?>

2. Retrieving a Cookie Value

To check if a cookie is set and get its value, use the $_COOKIE superglobal array. Use isset() to avoid errors if the cookie doesn't exist.

<?php
    if(!isset($_COOKIE["user"])) {
        echo "Cookie named 'user' is not set!";
    } else {
        echo "Cookie 'user' is set!<br>";
        echo "Value is: " . $_COOKIE["user"];
    }
?>

3. Modifying and Deleting

To modify a cookie, just set the cookie again using the setcookie() function with the same name. To **delete** a cookie, use the setcookie() function with an expiration date in the past.

<?php
    // Delete cookie by setting expiry to 1 hour ago
    setcookie("user", "", time() - 3600, "/");
?>
Safety Warning: Cookies are stored on the user's machine, meaning they can be seen and edited by the user. Never store sensitive data like passwords or credit card info in cookies.
Pro Tip: Use the httponly parameter (set to true) to prevent Javascript from accessing the cookie, which helps protect against XSS attacks.

Key Takeaways

  • Cookies store data on the client side (browser).
  • Use setcookie() to create, modify, and delete data.
  • Always provide a path (usually "/") to make cookies available across your site.
  • Cookies are great for non-sensitive preferences like theme (dark/light mode).
  • Retrieve values using the $_COOKIE array.