Session
Introduction
Session is a way to store information to be used across multiple pages.
Server assigns a unique id to each session. Variable content can be "remembered" without the need to pass it through URL or form.
session_start(); is used to start a session.
$_SESSION['variable'] = 'value'; is used to store a value in session.
session_destroy(); is used to destroy a session (Clear all session variables).
Code - session.php
<?php
session_start();
if(isset($_SESSION['color'])){
$color = $_SESSION['color'];
}
if(isset($_GET['color'])){
$_SESSION['color'] = $_GET['color'];
$color = $_GET['color'];
}
echo '<span style="color:'.$color.'">Color stored in session is: '.$color.'</span><p>';
echo '<a href="session.php?color=red">Red</a><br>';
echo '<a href="session.php?color=blue">Blue</a><br>';
echo '<a href="session.php?color=green">Green</a><p>';
echo '<a href="session.php">Refresh page without choosing color</a>';
echo '<p><a href="destroy.php">Destroy session</a>';
?>
Code - destroy.php
<?php
session_start();
session_destroy();
echo 'Session destroyed';
echo '<p><a href="session.php">Back to session.php</a>';
?>
Task
Say "Hello" to new user and "Welcome back" to returning user.
Provide a reset link to destroy the session.