Sling Academy
Home/PHP/How to use cookies in PHP

How to use cookies in PHP

Last updated: January 12, 2024

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, "/");

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.

Next Article: How to use sessions in PHP

Previous Article: How to fetch HTML content from URL in PHP

Series: Building Dynamic Web Pages with PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array