How to use cookies in PHP

Updated: January 12, 2024 By: Guest Contributor Post a comment

Overview

When developing web applications, cookies are an essential component in managing user sessions and preferences on the client’s browser. Cookies are small bits of data stored by the browser and are sent back to the server with every request. In this comprehensive guide, you will learn how to use cookies in PHP to enhance your web application’s persistence and user experience.

Managing Cookies in PHP

What are Cookies?

Cookies are a basic mechanism for storing data on the client side and are part of the HTTP protocol. Websites use cookies to remember information between page requests. Clients may use multiple cookies, and each one represents a small portion of data, such as a user identifier or session token.

Setting Cookies in PHP

To create a cookie in PHP, you use the setcookie() function. Here’s its basic syntax:

bool setcookie (string $name [, string $value = "" [, int $expires = 0 [, string $path = "/" [, string $domain = "" [, bool $secure = FALSE [, bool $httponly = FALSE ]]]]]])

The only required parameter is $name, which specifies the name of the cookie. Other parameters are optional and serve the following purposes:

  • $value – The data you want to store in the cookie.
  • $expires – The expiry time of the cookie. It’s a Unix timestamp, so you can use time() plus the number of seconds until expiration.
  • $path – Limits the cookie to a specific directory and its subdirectories on the server.
  • $domain – Limits the cookie to a specific domain and all its subdomains.
  • $secure – When TRUE, the cookie will only be sent over secure connections (HTTPS).
  • $httponly – When TRUE, the cookie will be accessible only through the HTTP protocol and not via scripting languages like JavaScript. This helps mitigate some types of cross-site scripting attacks (XSS).

Here is an example of setting a cookie:

setcookie("user_id", "12345", time() + (86400 * 30), "/"); // 86400 = 1 day

Accessing Cookies in PHP

All cookies sent by the browser in the HTTP request can be accessed in PHP via the $_COOKIE superglobal array. If a cookie named “user_id” was set, it can be accessed like this:

if (isset($_COOKIE["user_id"])) {
    echo 'User ID: ' . htmlspecialchars($_COOKIE["user_id"]); // Always filter cookies input
} else {
    echo 'User ID cookie is not set.';
}

Modifying and Deleting Cookies

To modify a cookie in PHP, you simply set another cookie with the same name. To delete a cookie, you set the expiration date to a time in the past:

// Modify a cookie
setcookie("user_id", "67890", time() + (86400 * 30), "/");

// Delete a cookie
setcookie("user_id", "", time() - 3600, "/");

Cookie Security and Best Practices

Handling cookies with care is essential for the security of your website. Here are some best practices:

  • Sensitive Data: Do not store sensitive data directly in cookies due to the risk of interception by malware or a malicious user.
  • Secure Flag: When using cookies to store login or session info, always use the secure flag to ensure cookies are sent over HTTPS only.
  • HTTP Only: Set the httponly flag for cookies to help prevent access through client-side scripts and reduce the risk of XSS attacks.
  • Validate Input: Always validate cookie values on the server-side to prevent injection attacks.

Conclusion

Cookies are a powerful way to maintain state between the server and the client. PHP’s built-in setcookie() handling makes it easy to set and retrieve cookies. Remember to adhere to security best practices to keep your user data safe and secure. With this guide, you’re now equipped to properly implement cookies in your PHP web applications.