PHP Session | PHP Tutorial For Beginners

A session variable stores information about a user across multiple pages. Sessions work by creating a unique ID for each visitor and associating variables with that ID, preventing two users' data from getting confused with one another.

Syntax: $_SESSION['variable_name']

How to Start a PHP Session

You must call session_start() at the very beginning of your PHP file — before any HTML output is sent to the browser.

<?php
session_start(); // must be the first thing in the file
?>

Storing and Retrieving Session Data

$_SESSION is an associative array. Assign to it to store data; read from it to retrieve.

<?php
session_start();
$_SESSION['topic'] = "PHP Session example."; // store
echo $_SESSION['topic'];                      // retrieve
// Output: PHP Session example.
?>

Counting Page Visits with a Session

This example tracks how many times a visitor has loaded a particular page:

<?php
session_start();
$_SESSION['number'] = isset($_SESSION['number'])
    ? $_SESSION['number'] + 1
    : 1;
?>
This is your <?php echo $_SESSION['number']; ?> visit to this page.

Destroying Session Data

To remove a single session variable, use unset():

<?php
session_start();
if (isset($_SESSION['topic'])) {
    unset($_SESSION['topic']);
}
?>

To completely destroy the entire session (e.g. on logout):

<?php
session_start();
session_destroy(); // removes all session data
?>

Hope this tutorial is useful for you. Keep following PHP Tutorial for Beginners for more help.

← Older Post Newer Post →