Session Variables

When a browser loads a new web page, it forgets all the information from the previous page. A PHP session is a way of storing information within a website, so that it can be retained and used across multiple pages.
Examples of session use are:

  • displaying a user’s id on multiple pages, following a successful login
  • retaining selected items in a shopping cart, as the user navigates from page to page
  • retaining values, such as a user’s quiz Score, when each new question page loads

Starting a session

The following PHP function is used to start a session. This should be placed at the top of a page, before any HTML code. If data is being passed between multiple pages, each page that requires access to the session should contain the PHP code below.

When a new session starts, a user key is stored on the user’s computer. The session_start() function looks to see if a user key exists. If it does, the current session is continued. If no user key exists, a new session is started.

<?php
   session_start();
?>
<!DOCTYPE html>
<html>
<head>

 

Session Variables

Session variables can be assigned values, or have their values checked in any file that contains the session_start() function.

if (!isset() {$_SESSION['loggedin']) {
    $_SESSION['loggedin'] = False;
}
...
$_SESSION['username'] = $username;
if ($_SESSION['loggedin'] == True) {
    echo "<p>Logged in as: " . $_SESSION['username'] . "</p>";
    // display rest of page
} else {
    echo "<p>Not logged in</p>";
    // display page with a login button
}

Ending a session

The PHP function session_destroy() is used to end a session. In this example, logout.php is ran when a “Log Out” button on other pages is clicked. The code below destroys the session and then reloads the home page.

<?php
    session_start();
?>
 
<?php
    session_destroy();
    include "index.php";
    die;
/php>