PHP Sessions

PHP sessions are a way to store data across multiple pages for individual users. They're commonly used to maintain user state and data (like login status, shopping carts, or preferences) throughout a browsing session.

Basics of PHP Sessions

1. Starting a Session

To start a session in PHP, you use the session_start() function. This must be called before any output is sent to the browser:

<?php session_start(); ?>

2. Storing Data in a Session

Once the session is started, you can store values in the $_SESSION superglobal array:

$_SESSION['username'] = 'JohnDoe'; $_SESSION['loggedin'] = true;

3. Accessing Session Data

You can access session data on any page after calling session_start():

echo $_SESSION['username']; // Outputs: JohnDoe

4. Removing Session Data

  • To remove a specific session variable:

unset($_SESSION['username']);
  • To remove all session variables:

session_unset();
  • To destroy the session entirely:

session_destroy();

How It Works

  • PHP generates a unique session ID for each user.

  • This session ID is typically stored in a cookie (PHPSESSID) on the client's browser.

  • On each request, PHP uses this ID to access the associated session data stored on the server.

Common Uses

  • Login and authentication systems

  • Shopping carts

  • Flash messages (temporary success or error notifications)