Sessions help remember information about a user while they browse your website. This way, you can keep users logged in or save their preferences.
0
0
Starting and using sessions in PHP
Introduction
When you want to keep a user logged in across different pages.
When you need to save user choices like language or theme during their visit.
When you want to store temporary data like items in a shopping cart.
When you want to track user activity without asking them to log in again.
When you want to pass information between pages without showing it in the URL.
Syntax
PHP
<?php session_start(); // Now you can use $_SESSION to store or get data $_SESSION['key'] = 'value'; ?>
You must call session_start() before any HTML or output.
Use the $_SESSION array to save or read session data.
Examples
Starts a session and saves the username 'Alice' in the session.
PHP
<?php session_start(); $_SESSION['username'] = 'Alice'; ?>
Starts the session and prints the saved username.
PHP
<?php session_start(); echo $_SESSION['username']; ?>
Counts how many times the user has visited the page during the session.
PHP
<?php session_start(); if (!isset($_SESSION['visits'])) { $_SESSION['visits'] = 1; } else { $_SESSION['visits']++; } echo "Visit number: " . $_SESSION['visits']; ?>
Sample Program
This program counts how many times a user visits the page in one session. Each time the page reloads, the counter increases by one.
PHP
<?php session_start(); if (!isset($_SESSION['counter'])) { $_SESSION['counter'] = 1; } else { $_SESSION['counter']++; } echo "You have visited this page " . $_SESSION['counter'] . " times during this session."; ?>
OutputSuccess
Important Notes
Sessions use cookies by default to keep track of users.
Always call session_start() at the very top of your PHP file before any output.
Session data is stored on the server, so it is safer than passing data in URLs.
Summary
Sessions let you save user data across multiple pages.
Always start a session with session_start() before using $_SESSION.
Use sessions to keep users logged in or remember their choices.