Day 20: Session in PHP

Session is a way to make data accessible on various pages of the website. Session stores on server and secure then the cookies.

Sessions are also used to store individual user data against a unique SessionId and SessionId can be used to share user information between pages requested. In session variable we can store string values as well as object.

session_start() function is used to start a function.

$_SESSION is a global variable to set the Session in PHP.

Program 59: Storing and Accessing Session Variables

<?php
session_start(); // Start the session
$_SESSION[“user”] = “Jhon”;
echo “Value in Session is “.$_SESSION[“user”];
?>

Program 60: Counter example with Session

<?php
session_start();
if( isset( $_SESSION[‘counter’] ) ) {
$_SESSION[‘counter’] += 1;
} else {
$_SESSION[‘counter’] = 1;
}
echo $_SESSION[‘counter’];
?>

Explanation:
isset() function is used to check if session variable is already set or not. In the above example every time you refresh the page counter value will get incremented.

Program 61: Destroy a PHP Session

<?php
session_start();
unset($_SESSION[‘counter’]); // unset a single session variable
session_unset(); // remove all session variables
session_destroy(); // destroy all the sessions
?>

Leave a Reply