Overview of This Lesson

Refresh this page because I am probably still making changes to it.

In this lesson we learn how we can use PHP Sessions to remember data between request-response cycles and why this is important.

Resources

The PHP Manual has a nice page with everything you would want to know about sessions in PHP.

Introduction to PHP Sessions

HTTP is stateless. When you make a request, the request is sent to the server and then the connection is terminated. When the response is sent back, it is sent from the server to the client, and the connection is again terminated. HTTP doesn't "remember" anything about previous requests and responses: When you click a link on a page, the server doesn't remember any of your previous requests or information about those requests. This is unlike FTP (File Transfer Protocol, which you might have used if you've ever uploaded/downloaded files using a client such as FileZilla or CoreFTP), which is stateful. FTP maintains the connection between the client and the server and keeps track of state information about the connection.

server doesn't remember you between request/response cycles
HTTP is Stateless: the server doesn't remember you between request/response cycles

The problem with a stateless protocol like HTTP is that you (as a developer) often need to keep track of information about the user/client between requests. For example, if your site is an online store, you need to keep track of what items the user adds to their shopping cart as they navigate from one page to another. Each time the user requests a new page, how does the server "remember" what items the user already had in their cart?

One way to remember this kind of information is by using cookies. Cookies are permanent but they can only store small amounts of text data. Additionally, many more savvy users block cookies in their browser, as a privacy measure.

Another option many PHP developers prefer are sessions.

A session is a visit to a web site or application: A session consists of a user first loading your site/application, using and/or navigating around the site/application, and then leaving the site/application.

A Session begins when a user accesses your application (any page, generally). A Session ends when one of the following happens:

When a Session is first created, a unique session ID is generated for that session. The server stores the session ID along with any other user data that was included in the request. The server then sends the session ID back to the client in the response. The client reads the session ID and stores it in as a session cookie.

new session starts when request is first made, server generating a unique session id, sending it back to client in the response
The server generates a unique session ID which is stored as a session cookie on the client machine

For the next request, and all subsequent requests, the session id stored in the session cookie is sent along in the request object. The server then reads the session ID in the request and matches it to table of session data it has: the session data with the same session ID belongs to that specific user during this current session. Any new data can be added and associated with that same session ID as neeeded.

the second and subsequent requests sending the session id to the server, server looks up the session id to access stored user data
Every request sends the session ID to the server so the server can look up the user's stored data for that session.

When the session expires or is terminated, the server deletes the stored session data and releases the session ID and its resources. After this occurs, the server doesn't remember the user or any of the stored data.

A developer can use a session variable to keep track of information as the user navigates around the site, making different requests of the server. For example, as the user shops around on your store's site, session variables can be used to remember the items in a shopping cart. When the user navigates to a new page, that page is requested using a new HTTP connection: the page's code can use a special session ID to add, read, and edit session variables stored on the server.

Sessions can somtimes be more advantageous than regular cookies: Cookies are stored on the user's computer, and many users not wishing to have their privacy violated will configure their browser to refuse cookies but still allow session cookies (although you will still have to add fallback code if the user has chosen to block all cookies).

Additionally, cookies can only store text data and to a maximum of 4096 bytes (that includes the cookie name, expiry date, the cookie's value, etc). PHP Sessions don't have a maximum size, and can contain text, numbers, arrays, or entire objects. However, the server running the PHP scripts does have a configuration option called memory_limit, which defines the maximum amount of memory allocated to a running script; the default value is 128MB so clearly you wouldn't want to store anything in a session that's close to 128MB in size.

In PHP, session information is stored in the global variable called $_SESSION. $_SESSION is an associative array where keys reference objects and values that you can add, edit, and remove.

You programmatically start a session when the user visits one of your pages, and the session ends when they leave your page, although you can also programmatically remove data from the session and/or end the session.

Creating a Session

The first thing that you need to do if you want to store and access session data is begin a session. This needs to be done on every page of your site that is going to use the session data.

To start a session, we invoke the session_start() function. The session_start() function will:

The session_start() function call must be the first line of PHP code in your page, and must even go above the HTML <!DOCTYPE> declaration.

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

Furthermore, the call to session_start() must be in every single page on your site that uses the session variables.

Each session is assigned a unique Session ID. This identifies each session as unique to a single user. session_start() checks to see if a session with a specific session ID already exists or not. It generates a new session ID if it needs to create a new sessions.

When a session is created and when data is added to the session, the $_SESSION global associative array is automatically populated with any session data stored on the server.

Adding and Reading Session Data

Once you have started or resumed a session, you can add data to it. You simply make up a key and store your data as the value in the $_SESSION variable. You can then read it back using the same key:

<?php
    session_start();

    $_SESSION["example1"] = "Hello, World!";
?>
<!DOCTYPE>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Sessions Examples</title>
  </head>
  <body>
    <h1>Sessions Examples</h1>
    <div><?php echo $_SESSION["example1"] ?></div>
  </body>
  </html>

Note that you'll get an error if you try to access a session key that doesn't exist:

<?php
    session_start();

    // -- code to show error messages:
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    // -------------

    $_SESSION["example1"] = "Hello, World!";
?>
<!DOCTYPE>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Sessions Examples</title>
  </head>
  <body>
    <h1>Sessions Examples</h1>
    <div><?php echo $_SESSION["example1"] ?></div>
    <div><?php echo $_SESSION["example2"] ?></div>
  </body>
  </html>

When you load this page, you'll see an error on your page similar to the one below (obviously my path and line # might be different from yours):

Notice: Undefined index: example2 in C:\Users\Wendi\Syst10199\projects\PHPExamples\index.php on line 14

In an earlier lesson, we learned the isset() function. We can use that to see if a session variable was set or not. If a session variable was not set, it means it doesn't yet exist (perhaps this is the user's first visit in the session).

<?php
    session_start();

    // -- code to show error messages:
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    // -------------

    $_SESSION["example1"] = "Hello, World!";
    $ex2 = isset($_SESSION["example2"]) ? $_SESSION["example2"] : "no data set";
?>
<!DOCTYPE>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Sessions Examples</title>
  </head>
  <body>
    <h1>Sessions Examples</h1>
    <div><?php echo $_SESSION["example1"] ?></div>
    <div><?php echo $ex2 ?></div>
  </body>
  </html>

In the code above, we've added a line of code (line 4) that checks to see if $_SESSION["example2"] exists. If it does, we store that session variable in the scalar variable $ex2. If the $_SESSION["example2"] session variable doesn't exist, we store the string literal "no data set" in the $ex2 variable. When you load the page, you'll see "no data set" echoed onto the screen, because we've never created the example2 session variable.

Try adding some code at the bottom of the page that assigns a value to the example2 session variable, then reload the page and see if that value outputs onto the screen.

You can modify a session variable any time using an assignment statement, e.g. $_SESSION["example1"] = "Bye";

Removing Session Variables and Ending Sessions

If you need to, you can remove session variables so that they no longer exist. To remove a session variable, use the unset() function. Pass the function the session variable you want to unset:

unset($_SESSION["example1"]);

To unset all of the session variables, use the session_unset() function:

session_unset();

If you want to end a session, use the session_destroy() function:

session_destroy();

This will destroy the session data for the current session. However, this won't destroy the session cookie on the client machine and won't necessarily destroy any global session variables.

If you want to destroy a session, a better way is to simply delete all the session data manually:

$_SESSION = array();

This still won't delete the session cookie, but that's fine. If you really want to destroy the cookie, check the PHP Manual entry for session_destroy() for some code that deletes the session cookie.

Note that a session will automatically destroy itself a certain amount of time after the user closes the browser, navigates away from your site, or remains inactive for a period of time. You don't necessarily have to end the session unless you want to make sure it ends while the user is still on your site. The amount of time it takes a session to end automatically depends on the server settings: there is an option called "session.gc_maxlifetime" that sets the amount of time a session should stay alive.

Exercises

1. Add a file sessionTest1.php to your project and paste in the following code:

<?php
session_start();
$random = isset($_GET["random"]) ? htmlentities($_GET["random"]) : 0;
$cancel = isset($_GET["cancel"]) ? htmlentities($_GET["cancel"]) : "no";

if (!isset($_SESSION["test"])) {
    echo "<p>No session found - starting a session now.</p>";
    $_SESSION["test"] = $random;   
} else {
    echo "<p>Session found: " . $_SESSION["test"] . "</p>";   
}
if ($cancel == "yes") {
    echo "<p>Clearing Session...</p>";
    session_destroy();
}
echo "<p><a href='sessionTest1.php?random=".rand(1,10000)."&cancel=no'>Reload this page</a></p>";
echo "<p><a href='sessionTest1.php?cancel=yes'>Destroy session</a></p>";
?>

2. Add a second page to your project called sessionTest2.php. Add the following code:

<?php
session_start();
$cancel = isset($_GET["cancel"]) ? htmlentities($_GET["cancel"]) : "no";
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">

        <title>Exercise 2</title>
    </head>
    <body>

        <?php
            //retrieve session data
            echo "<p>Pageviews=" . $_SESSION['views'] . "</p>";
        ?>
        
        <h1>Exercise 2</h1>
        
        <?php
        if (isset($_SESSION['views']))
            $_SESSION['views'] = $_SESSION['views'] + 1;
        else
            $_SESSION['views'] = 1;
        
        echo "<h2>Same Page</h2>";
        echo "<p>Views=" . $_SESSION['views'] . "</p>";
        
        if ($cancel == "yes") {
            echo "<p>Clearing Session...</p>";
            session_destroy();
        }
        
        echo "<p><a href='sessionTest2.php'>Reload this page</a></p>";
        echo "<p><a href='sessionTest2.php?cancel=yes'>Destroy session</a></p>";
    ?>
    </body>
</html>

3. Add a new HTML file to your project called sessionTest3.html and paste the following into the BODY element:

<p>Passing values from JS to PHP<p>
<script type="text/javascript">
  width = screen.width;
  height = screen.height;
  if (width > 0 && height > 0) {
      window.location.href = "sessionTest3.php?width=" + width + 
        "&height=" + height;
  } else
      exit();
</script>

Now add a PHP file and call it sessionTest3.php. Add the following code:

<?php
session_start();
$width = isset($_GET["width"]) ? htmlentities($_GET["width"]) : 0;
$height = isset($_GET["height"]) ? htmlentities($_GET["height"]) : 0;

if ($width >= 0) {
    $_SESSION['width'] = $width;
}
if ($height >= 0) {
    $_SESSION['height'] = $height;
}
echo "<h1>Screen Resolution:</h1>";
echo "Width: $width<br>";
echo "Height: $height<br>";
?>

Now return to your sessionTest2.php file and add the following code on line 30:

echo "<p>" . $_SESSION["width"] . " x " . $_SESSION["height"] . "</p>";

4. Add new new pages to your project: sessionTest4a.php and sessionTest4b.php. Each file should have the following content:

// sessionTest4a.php:
<?php
    session_start();
    
    $reset = isset($_GET["reset"]) ? htmlentities($_GET["reset"]) : "false";
    if ($reset) {
        session_destroy();
    }
    
    $name = isset($_SESSION["userName"]) ? htmlentities($_SESSION["userName"]) : "";
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">

        <title>Example 4</title>
    </head>
    <body>
        <h1>Example 4</h1>
        
        <form method="post" action="sessionTest4b.php">
            <input type="text" name="txtName" placeholder="Enter your name."
            value='<?=$name?>'>
            <input type="submit">
            <a href="sessionTest4a.php?reset=true">Log Out</a>
        </form>
    </body>
</html>
// sessionTest4b.php:
<?php
    session_start();
    $name = isset($_POST["txtName"]) ? htmlentities($_POST["txtName"]) : "";
    if (!empty($name)) {
        $_SESSION["userName"] = $name;
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">

        <title>Example 4</title>
    </head>
    <body>
        <h1>Example 4</h1>
        
        <?php 
        if (!empty($name)) {
            echo "<h2>Welcome, $name!</h2>";
        } else {
            echo "<h2>Welcome!</h2>";
        }
        ?>
        
        <a href="sessionTest4a.php">Back to First Page</a>
    </body>
</html>

5. Now that you've completed each exercise, add the following statement to sessionTest4b.php in the body of the document after the if/else blocks:

var_dump($_SESSION);

6. Create a simple page that lets you manage your session variables. Provide a list of check boxes for each session variable that currently exists so you can check off which ones you want to delete, and some input fields where you can add a new session variable.

Very simple UI for Session Variables
Select variables to remove and/or add a new session variable
After clicking SUBMIT on previous screen.

Tips: