0
0
PHPprogramming~5 mins

Session variables in PHP

Choose your learning style9 modes available
Introduction

Session variables let you save information about a user while they browse your website. This helps keep data like login status or preferences as they move between pages.

Remember if a user is logged in across different pages.
Store items in a shopping cart while the user shops.
Keep track of user preferences like language or theme.
Save temporary data during a multi-step form.
Pass data between pages without showing it in the URL.
Syntax
PHP
<?php
session_start();
$_SESSION['key'] = 'value';
$value = $_SESSION['key'];
?>

You must call session_start() at the very start of your PHP script before any output.

Session variables are stored in the $_SESSION superglobal array.

Examples
Save the username 'Alice' in a session variable.
PHP
<?php
session_start();
$_SESSION['username'] = 'Alice';
?>
Retrieve and show the username stored in the session.
PHP
<?php
session_start();
echo $_SESSION['username'];
?>
Add an item to a shopping cart stored in the session.
PHP
<?php
session_start();
if (isset($_SESSION['cart'])) {
    $_SESSION['cart'][] = 'item1';
} else {
    $_SESSION['cart'] = ['item1'];
}
?>
Sample Program

This program starts a session, saves the user's name and role, then prints them out.

PHP
<?php
session_start();

// Save user info
$_SESSION['user'] = 'Bob';
$_SESSION['role'] = 'admin';

// Show saved info
echo "User: " . $_SESSION['user'] . "\n";
echo "Role: " . $_SESSION['role'] . "\n";
?>
OutputSuccess
Important Notes

Always call session_start() before using $_SESSION.

Session data is stored on the server, so it is more secure than cookies.

To remove a session variable, use unset($_SESSION['key']);.

Summary

Session variables store user data across pages.

Use session_start() to begin using sessions.

Access session data with the $_SESSION array.