Skip to content

PHP Tutorial Sessions and Cookies

What Is a Session?

Lesson 176 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

HTTP, the protocol of the web, has no memory. Every request is separate. When a visitor opens page two, the server has no idea that the same person was on page one a second ago.

A session adds that memory. It is a small storage area on the server that belongs to one visitor.

An everyday picture

Think of a cloakroom at a theatre. You hand in your coat and receive a numbered ticket. Later you show the ticket, and the staff find your coat. They do not need to remember your face.

In PHP:

  • The coat is your session data (the visitor’s cart, login, language).
  • The ticket is the session ID, a long random string.
  • The cloakroom is the server’s session storage.

How a session works

  1. A visitor opens a page that calls session_start().
  2. PHP creates a session with a random ID and sends the ID to the browser in a cookie (named PHPSESSID by default).
  3. The browser sends that cookie back with every later request.
  4. PHP finds the saved data for that ID and puts it into $_SESSION.

The browser only carries the ID. The data stays on the server, so the visitor cannot read or edit it.

What sessions are used for

  • Keeping a user logged in.
  • A shopping cart before checkout.
  • Flash messages such as “Profile saved”.
  • A CSRF token that protects forms.
  • Multi-step forms (step 1, step 2, step 3).

What sessions are not for

  • Long-term data. Sessions expire. Store anything that must last in the database.
  • Large data. Each visitor has their own session, so big values add up.
  • Settings that must survive for months (use a cookie or the database).

Where session data lives

By default, PHP saves each session as a file in a temporary folder on the server. Larger sites move sessions to a database, Redis or Memcached. Your code stays the same, because you only use $_SESSION.

The lifetime

A session ends when:

  • The visitor’s browser forgets the session cookie (by default when the browser closes).
  • The server removes it after a period of inactivity (the garbage collector, controlled by session.gc_maxlifetime, 1440 seconds by default).
  • Your code destroys it (for example on logout).
info
Next steps
The following lessons show how to start a session, store and read data, destroy it and keep it secure.