0
0
PHPprogramming~5 mins

How sessions work in PHP

Choose your learning style9 modes available
Introduction

Sessions help remember who you are when you visit different pages on a website. They keep your information safe while you browse.

When a user logs into a website and you want to keep them logged in as they move between pages.
When you want to save items in a shopping cart while the user shops online.
When you need to store user preferences temporarily during a visit.
When you want to track user activity without asking them to log in again on every page.
Syntax
PHP
<?php
session_start();
$_SESSION['key'] = 'value';
$value = $_SESSION['key'];
?>

session_start() must be called before any HTML or output.

Use $_SESSION superglobal array to store and access session data.

Examples
Start a session and save the username 'Alice' in the session.
PHP
<?php
session_start();
$_SESSION['username'] = 'Alice';
?>
Start the session and print the saved username.
PHP
<?php
session_start();
echo $_SESSION['username'];
?>
Remove the 'username' from the session data.
PHP
<?php
session_start();
unset($_SESSION['username']);
?>
Sample Program

This program starts a session, saves the name 'Bob' in the session, and then prints a greeting using that name.

PHP
<?php
// Start the session
session_start();

// Save user data in session
$_SESSION['user'] = 'Bob';

// Retrieve and print user data
echo "Hello, " . $_SESSION['user'] . "!";
?>
OutputSuccess
Important Notes

Always call session_start() at the very top of your PHP file before any output.

Sessions use cookies by default to keep track of users, so cookies must be enabled in the browser.

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

Summary

Sessions let websites remember you as you move between pages.

Use session_start() to begin a session and $_SESSION to store data.

Session data is saved on the server and linked to your browser via a cookie.