AdyBlaze
Latest Article

PHP Cookies Explained with Examples (Beginner Guide 2026)

23 Jul 2026

WhatsApp Facebook Telegram

Introduction

Cookies are small pieces of data stored in the user’s browser. Unlike sessions, which store data on the server, cookies store information on the client’s device.

Cookies help websites remember users even after they close and reopen their browser.

They are widely used for:


What is a Cookie?

A cookie is a small text file created by the server and stored in the browser.

When the user visits the website again, the browser sends the cookie back to the server.

This allows PHP to recognize returning visitors.


How Cookies Work

  1. User visits the website.
  2. PHP creates a cookie.
  3. Browser stores the cookie.
  4. User revisits the website.
  5. Browser sends the cookie back automatically.
  6. PHP reads the stored value.

Creating a Cookie

Use the setcookie() function.

<?php

setcookie(
    "username",
    "Malik",
    time() + 86400,
    "/"
);

echo "Cookie Created";

?>

This cookie expires after 1 day.


Reading a Cookie

<?php

if(isset($_COOKIE["username"])){

    echo "Welcome " . $_COOKIE["username"];

}

?>

Output

Welcome Malik

Updating a Cookie

Simply create the cookie again with a new value.

<?php

setcookie(
    "username",
    "Adil",
    time()+86400,
    "/"
);

?>

The old value is replaced.


Deleting a Cookie

To delete a cookie, set its expiration time to the past.

<?php

setcookie(
    "username",
    "",
    time()-3600,
    "/"
);

?>

The browser removes the cookie.


Cookie Lifetime

Common expiration examples:

time() + 3600
time() + 86400
time() + (86400 * 30)

Real-World Example

Remember the user’s preferred theme.

<?php

setcookie(
    "theme",
    "dark",
    time()+86400*30,
    "/"
);

?>

Later:

<?php

if(isset($_COOKIE["theme"])){

    echo "Theme: " . $_COOKIE["theme"];

}

?>

Cookies vs Sessions

CookiesSessions
Stored in browserStored on server
Can persist for days/monthsUsually expire when session ends
Limited storageLarger storage
User can delete themManaged by server
Best for preferencesBest for authentication

Security Tips


Common Mistakes

❌ Storing confidential information

❌ Creating cookies after HTML output

❌ Assuming cookies always exist

❌ Trusting cookie values without validation


Frequently Asked Questions

Where are cookies stored?

In the user’s web browser.


Can users delete cookies?

Yes. Users can clear cookies from browser settings.


Are cookies secure?

Cookies are useful but should never store sensitive information such as passwords or payment details.


Conclusion

Cookies help websites remember users, preferences, and settings across multiple visits. Combined with PHP Sessions, they form the backbone of personalization and authentication in modern web applications.

Understanding cookies is essential for building user-friendly PHP websites.


Next Tutorial

PHP File Upload Explained with Examples (2026 Guide)