Begin Web Programming with PHP & MySQL

Advertisements



PHP Session

A session is started with the session_start() function at the very beginning of the PHP page. A session variable is set with the PHP global variable $_SESSION.

Eg:
Create a page index.php and put the code below.
<?php
session_start(); // session start before HTML
?>
<!DOCTYPE html>
<html>
<body>
<?php
// set session variables
$_SESSION["student_id"] = 5;
$_SESSION["username"] = "jamesbond";
echo "Student id is : ".$_SESSION["student_id"];
?>
</body>
</html>

Accessing a PHP session variable

Session variables are not passed individually to each php page, instead they are retrieved from the session we open at the beginning of each page - session_start(). We can access and change the value of the session variable from any page where the session is started.

Create a page dashboard.php and put the code below.
<?php
session_start();
$_SESSION["username"] = "jamesbond";
echo "Username before changing : ".$_SESSION["username"];
$_SESSION["username"] = "danielcraig";
echo "<br>Username after changing : ".$_SESSION["username"];
?>

Destroy a PHP session variable

The web server will terminate the session upon closing the browser. We can destroy it manually using the PHP in-built functions session_unset() and session_destroy(). Create a page logout.php and put the code below.
<?php
session_start();
session_unset(); // remove all the session variables
session_destroy(); // destroy the current session
?>