Sessions

This YouTube video was created by Steve Griffith.

Like a cookie, a session is a way to store information to be used across multiple pages; however, with a session, the information is store on the server, not the user's computer and only lasts until the user closes the browser.

Starting a Session

In PHP, to start a session the session_start() function must be invoked. When the function is called, PHP automatically opens and reads the current session. The session_start() method will need to be invoked on every page that requires a session and should be called before outputting anything to the browser.

Creating Session Data

Once the session_start() function is invoked, the $_SESSION array can be used. The [$_SESSION] array is an associative array containing a session variable available to the current script. Like any other associative array, new items can be added to the session using bracket notation.

<?php
// page1.php
session_start();

$_SESSION['name'] = 'Michael';

header('Location: page2.php');
<?php
// page2.php
session_start();

echo $_SESSION['name']; // Michael

Editing Session Data

Because the $_SESSION variable is an associative array, we can manipulate its values in the same way as any other array.

<?php
// page1.php
session_start();

$_SESSION['name'] = 'Michael';
echo $_SESSION['name']; // Michael

$_SESSION['name'] = 'Joe'; 
echo $_SESSION['name']; // Joe

Removing Session Data

The unset method can be used to remove a variable from the Session.

<?php
// page1.php
session_start();

$_SESSION['name'] = 'Michael';
echo $_SESSION['name']; // Michael

unset($_SESSION['name']);
echo $_SESSION['name']; // null