Working With Sessions and Cookies in PHP

How PHP stores user data, remembers login states, and powers modern web apps with sessions, cookies and secure auth.

How PHP stores user data, remembers login states, and powers modern web applications.

Introduction

Whenever you login to a website, add items to your cart, or return to a page and find it remembers your preferences — that's thanks to sessions and cookies.

These two features are essential to all web applications:

If you're building login systems, shopping carts, dashboards, or anything requiring user state — you must understand how both work.

This guide explains them simply with examples you can use right away.

1. What Are Cookies?

A cookie is a small piece of text stored on the user's browser.

Setting a Cookie in PHP

Reading a Cookie

Deleting a Cookie

Cookies are client-side , meaning they live in the user's browser.

2. What Are Sessions?

A session stores user data on the server and assigns it a unique ID.

Starting a Session

This must appear at the top of the page, before any HTML output.

Storing Data in a Session

Accessing Session Data

Destroying a Session

Sessions are more secure than cookies because the data stays on your server, not in the user's browser.

3. How Sessions and Cookies Work Together

This cookie does not contain data, only the session ID.

The user cannot read or modify the session data — it's all server-side.

4. Cookies vs Sessions (Quick Comparison)

Feature

Cookies

Sessions

Stored

Browser

Server

Size Limit

~4KB

Server memory

Security

Low

High

Lifetime

Controlled by expiry

Until session timeout

Best For

Preferences, tracking

Login, cart, secure data

Store sensitive data in sessions, not cookies.

5. Practical Example: Login System Flow

1. User logs in via form

2. Accessing protected pages

3. Logging out

6. Secure Cookie Tips

❗ Never store passwords or sensitive data in cookies

7. When to Use Cookies vs Sessions

Use Cookies When:

Use Sessions When:

8. Summary

Sessions and cookies form the foundation of all web apps. Master these and you can build authentication systems, dashboards, e-commerce carts, and more.

Related articles