Cookies - potatoscript/php GitHub Wiki

Cookies in PHP

Overview

Cookies are small pieces of data stored on the user's browser. They are often used to remember user preferences, login sessions, or tracking information. Unlike sessions, cookies are stored on the client side (in the browser), and the data persists across different sessions and page reloads.

In this section, we will cover:

  • Setting Cookies
  • Retrieving Cookies
  • Modifying Cookies
  • Deleting Cookies
  • Cookie Security Best Practices

Setting Cookies

To set a cookie in PHP, you use the setcookie() function. This function must be called before any output is sent to the browser. You can set a cookie to store simple data such as a user’s name or preferences.

Syntax:

setcookie(name, value, expire, path, domain, secure, httponly);
  • name - The name of the cookie.
  • value - The value of the cookie.
  • expire - The expiration date of the cookie (in seconds since the Unix Epoch). If omitted or set to 0, the cookie expires when the browser is closed.
  • path - The path on the server where the cookie is available.
  • domain - The domain the cookie is available to.
  • secure - If true, the cookie will only be sent over secure HTTPS connections.
  • httponly - If true, the cookie will be accessible only via the HTTP protocol, not JavaScript.

Example:

<?php
// Set a cookie that expires in 1 hour
setcookie("user", "JohnDoe", time() + 3600, "/");

// Check if the cookie is set
if (isset($_COOKIE["user"])) {
    echo "Hello, " . $_COOKIE["user"];
} else {
    echo "User cookie is not set!";
}
?>

Explanation:

  • setcookie("user", "JohnDoe", time() + 3600, "/"); sets a cookie named user with the value JohnDoe, and it will expire in 1 hour.
  • The cookie can be accessed through $_COOKIE["user"].

Retrieving Cookies

Cookies are automatically sent to the server with each request once they are set. You can retrieve a cookie's value using the $_COOKIE superglobal array.

Example:

<?php
// Retrieve the cookie value
if (isset($_COOKIE["user"])) {
    echo "Welcome back, " . $_COOKIE["user"];
} else {
    echo "No user cookie found.";
}
?>

Explanation:

  • $_COOKIE["user"] is used to access the value of the cookie. If the cookie exists, it will return the stored value.

Modifying Cookies

To modify a cookie, you can overwrite the cookie with a new value. The cookie will be updated in the browser on the next request. You can also change the expiration time or other properties.

Example:

<?php
// Modify the existing "user" cookie
setcookie("user", "JaneDoe", time() + 3600, "/");

// Retrieve the updated cookie value
echo "Updated User: " . $_COOKIE["user"];
?>

Explanation:

  • We overwrite the cookie user with a new value JaneDoe and update its expiration to 1 hour.

Deleting Cookies

To delete a cookie, you set its expiration time to a past value. The cookie will expire immediately, and the browser will remove it.

Example:

<?php
// Delete the "user" cookie
setcookie("user", "", time() - 3600, "/");

// Check if the cookie is deleted
if (isset($_COOKIE["user"])) {
    echo "Cookie is still set: " . $_COOKIE["user"];
} else {
    echo "Cookie has been deleted!";
}
?>

Explanation:

  • Setting time() - 3600 expires the cookie, effectively deleting it.

Cookie Security Best Practices

Although cookies are widely used, they can pose security risks if not handled properly. Below are some security best practices to ensure your cookies are secure:

1. Use the secure Flag:

Always use the secure flag to ensure that cookies are sent over HTTPS connections only. This prevents cookies from being sent over insecure HTTP connections, which could expose sensitive information.

setcookie("user", "JohnDoe", time() + 3600, "/", "", true, true);

2. Use the httponly Flag:

Set the httponly flag to true to prevent JavaScript from accessing the cookie. This mitigates the risk of XSS (Cross-Site Scripting) attacks.

setcookie("user", "JohnDoe", time() + 3600, "/", "", false, true);

3. Use the SameSite Attribute:

The SameSite cookie attribute helps mitigate CSRF (Cross-Site Request Forgery) attacks by restricting how cookies are sent in cross-site requests. The possible values are Strict, Lax, and None.

setcookie("user", "JohnDoe", time() + 3600, "/", "", false, true, "Strict");

4. Set a Short Expiry Time:

Cookies should have a reasonable expiration time, especially for sensitive information. Avoid setting cookies with long expiration times for security reasons.

5. Validate Cookie Data:

Never trust cookie data blindly. Always validate and sanitize the data retrieved from cookies to ensure it hasn't been tampered with.

Example:

<?php
if (isset($_COOKIE["user"])) {
    $user = filter_var($_COOKIE["user"], FILTER_SANITIZE_STRING);
    echo "Hello, " . $user;
}
?>

Explanation:

  • Use filter_var() to sanitize the cookie value and prevent injection attacks.

Conclusion

In this section, we covered:

  • Setting, retrieving, modifying, and deleting cookies in PHP.
  • Cookie security best practices, including using secure, HTTP-only, and SameSite attributes to protect cookie data.

Cookies are an important part of web development, especially for handling user preferences, authentication, and tracking. By following security best practices, you can use cookies safely and effectively in your PHP applications.