How to Use Cookies in PHP? (Create, Access, & Delete)

Mehul Patel
Mehul Patel
how to use cookies in php

You return to a website, and the user experience is much better–almost like it’s based around you. This small (sometimes massive) but powerful convenience is made possible by cookies, a core feature of web development.

Cookies in PHP let you store user data directly in the browser. That means personalized experiences, session management, and seamless navigation. And you can use it to implement a “Remember Me” feature, track user activity, or save preferences.

So this blog showcases how to use cookies in PHP, from setting and modifying to updating and deleting them. Let’s look at ways to harness them responsibly and effectively.

What is Cookies in PHP?

Cookies are small pieces of data stored in a user’s browser by a website. They allow web applications to remember information—like login sessions, shopping cart items, or language preferences—between visits.

How Cookies Work

  1. Server-Side Creation: A website (via PHP or another backend language) generates a cookie and sends it to the browser.
  2. Client-side Storage: The browser stores the cookie locally.
  3. Automatic Submission: With each subsequent request, the browser sends the cookie back to the server. That enables persistent user tracking.

Example of a Cookie in PHP

Here’s a breakdown of a real-world cookie, showing each component in action.

setcookie(
    "user_session",          // Name (identifier)
    "a1b2c3d4e5",            // Value (stored data)
    time() + 86400,          // Expiration (1 day from now)
    "/account",              // Path (only accessible in /account)
    ".example.com",          // Domain (works on all subdomains)
    true,                    // Secure (HTTPS only)
    true                     // HttpOnly (no JavaScript access)
);

What this cookie does:

  • Stores a session ID (a1b2c3d4e5) under the name user_session.
  • Expires in 24 hours. After that, the browser deletes it.
  • Restricted to /account path. It won’t be sent to other site sections.
  • Works on all subdomains (e.g., shop.example.com, blog.example.com).
  • Secure & HttpOnly, so it protects against theft and XSS attacks.

Using cookies can help with session management, personalization, and user behavior tracking and analysis. All in all, you can hire our expert PHP developers to implement cookies and build dynamic, user-friendly websites.

Want cookies and other advanced features on your PHP-powered website?

How to Set Cookies in PHP?

Cookies in PHP are created using the setcookie() function. It sends an HTTP header to the browser to store the data. Here’s the basic syntax:

setcookie(name, value, expire, path, domain, secure, httponly);
  • name (required): The cookie’s identifier (e.g., "username").
  • value (required): The data to store (e.g., "john_doe").
  • expire (optional): When the cookie expires (Unix timestamp).
  • path (optional): The server path where the cookie is valid (/ for the entire site).
  • domain (optional): The domain where the cookie works (example.com).
  • secure (optional): If true, send only over HTTPS.
  • httponly (optional): If true, prevents JavaScript access (security best practice).

Example of a Simple Cookie Setup

<?php

// Set a cookie that expires in 1 hour
setcookie("user", "Alice", time() + 3600, "/");
echo "Cookie 'user' has been set!";

?>

Example of a Secure, HTTP-Only Cookie

<?php

setcookie(
    "auth_token",
    "abc123xyz",
    time() + 86400, // Expires in 1 day
    "/",            // Available across the whole site
    "example.com",  // Domain
    true,           // HTTPS only
    true            // HTTP-only (no JS access)
);

?>

Make sure to set the cookies before any HTML output (headers are sent first).

How to Use Cookies in PHP?

Cookies enable websites to remember user data between page visits. You can use cookies in PHP through the $_COOKIE superglobal array. Here’s how to work with them effectively:

Retrieving the Cookies

To access a cookie, use PHP’s $_COOKIE superglobal array. Here’s an example:

<?php

if (isset($_COOKIE["user"])) {
    echo "Welcome back, " . htmlspecialchars($_COOKIE["user"]);
} else {
    echo "No user cookie found.";
}

?>

Always check if a cookie exists with isset() before accessing it. And use htmlspecialchars() to prevent XSS attacks when displaying cookie data.

Updating the Cookies

To modify a cookie, simply overwrite it using setcookie() with new values. Here’s an example:

<?php

if (isset($_COOKIE["user"])) {
    // Update the cookie to expire in 2 days
    setcookie("user", $_COOKIE["user"], time() + 172800, "/");
    echo "Cookie updated!";
}

?>

The browser must receive the updated cookie before changes take effect.

Deleting the Cookies

To remove a cookie, set its expiration to a past time. Here’s an example:

<?php

if (isset($_COOKIE["user"])) {
    setcookie("user", "", time() - 3600, "/");
    echo "Cookie deleted!";
}

?>

Make sure that the path and domain match the original cookie settings. Clearing the cookies will help maintain privacy and session control. For the best results with it, get our professional PHP development services. We will implement the best practices for effective results.

Best Practices for Using Cookies in PHP

Cookies are vital in conducting the best security practices in PHP. But, it also requires careful handling to ensure security, user privacy, and an optimized browsing experience.

Best Practices for Using Cookies in PHP

Cookies are an excellent way to enhance the user experience on the website. But improper use can lead to security risks and privacy concerns. So here are the key practices to follow.

Set Secure & HTTP-Only Flags

Always enable Secure (HTTPS-only) and HTTP-Only (blocks JavaScript access) to protect cookies from theft and XSS attacks:

setcookie("session_id", "abc123", time() + 3600, "/", "example.com", true, true);

Limit Cookie Lifetime

Avoid excessively long expiration times. Use short-lived sessions for sensitive data and renew them as needed:

setcookie("preferences", "dark_mode", time() + 86400); // 1 day

Sanitize & Validate Cookie Data

Never trust cookie values—always sanitize input to prevent injection attacks:

$clean_user = htmlspecialchars($_COOKIE['username']);

Avoid Storing Sensitive Data

Cookies are stored client-side and can be tampered with. Store session tokens instead of raw passwords or personal info.

Comply with Privacy Laws (GDPR, CCPA)

Inform users about cookie usage and obtain consent before setting non-essential tracking cookies.

Here’s a bonus tip. Use SameSite=Lax/Strict to prevent CSRF attacks in modern browsers.

Want help with your PHP web project?

FAQs About How to Use Cookies in PHP

What’s the difference between cookies and sessions?

Cookies store data in the browser, while sessions store data on the server (using a session ID in a cookie).

Are cookies secure for storing login sessions?

Cookies alone aren’t secure—always pair them with server-side sessions, HTTPS, and HttpOnly/Secure flags.

How do I make cookies work across subdomains?

Set the domain parameter to .example.com (with a leading dot) for cross-subdomain access.

Do cookies work if JavaScript is disabled?

Yes, since cookies are HTTP headers, they don’t rely on JavaScript—unlike localStorage.

Let’s Summarize

Cookies are a fundamental part of web development. You get personalized user experiences, session management, and seamless interactions. It’s important to understand when to set, retrieve, update, and delete cookies in PHP. That’s how you build more dynamic and user-friendly websites.

Remember to prioritize security with HttpOnly and Secure flags. And respect user privacy with proper consent mechanisms. Plus, make sure to always validate cookie data to prevent vulnerabilities.

And if you want help with implementing cookies on your website, hire our PHP development experts today!

author
Mehul Patel is a seasoned IT Engineer with expertise as a WordPress Developer. With a strong background in Core PHP and WordPress, he has excelled in website development, theme customization, and plugin development.

Related Blog Posts

NativePHP
PHP

NativePHP allows PHP developers to create desktop applications for Windows, macOS, and Linux using their existing skills. This guide covers how NativePHP works, setting it...

PHP SSH Server
PHP

Learn how to connect and manage remote servers using PHP SSH Server. Discover tools, libraries, and methods to automate tasks, run commands, and securely handle...

task reminder system in php
PHP

Discover how to build a powerful PHP-based task reminder system! This comprehensive guide will walk you through the entire process, from database design to user...