PHP sessions
Where are we?
This chapter is about restricting access to pages on a Web site. We just talked about the goal: a workflow with log in, actions, and log out.
This page talks about PHP sessions. We’ll use use to create the workflow we want.
This lesson’s goals
Learn that:
- Session memory is separate from any one page.
- Pages can store data in session memory, and retrieve it.
- Sessions can be destroyed by PHP pages. Sessions expire after a time of inactivity.
The goal
Louise works for DogToys, keeping product information up-to-date. Here’s one of Louise’s work sessions.

Figure 1. Louise’s work session
Louise logs in. Then she does her work: adding products, editing products, whatever she needs to do. At the end of the session, she logs out.
Once she has logged in, all of the pages – edit-product.php, add-product.php, and so on – know who she is, and what permissions she has. She doesn’t have to log in again for each change.
This is the workflow we want. But…
The problem
Each PHP page is a program running on the server. When the program starts running, it asks the server’s operating system for some memory, where it can store variables.

Figure 2. Page memory
Each time the code makes a new variable, a place is created for the variable in the page’s memory.
Here’s an important thing: when the page is finished, the page’s memory is erased. The server’s operating system grabs the memory back. So there’s nothing left of the variables. They’re all gone.
Every page has its own memory space:

Figure 3. Each page has some memory
All of the page memories are independent. Nothing is shared.
Remember we want to have a log in page, log-in.php. How does this page let the other pages know that Louise is allowed to use the system? log-in.php has to leave something behind to say, “Louise is OK.” But how?
That’s where PHP sessions come in. Sessions do a number of things, but the most important is that they create some memory on the server that exists separately from any one page:

Figure 4. Session memory
log-in.php can put variables into the session memory. When the server erases log-in.php’s memory, the session memory will still be there.
Other pages can access the session memory. add-product.php can look in it, and see what log-in.php left behind.
This is how we can make authentication work. When a user logs in, we can put some data into the session memory. Other pages can check the session memory, to see what the user is allowed to do.
Each person who connects to DogToys gets their own session memory:

Figure 5. Separate sessions
Actually, the server doesn’t create a separate session for each person, but for each browser that connects. Each browser will be running on a machine with a different IP address:

Figure 6. Sessions for IP addresses
There’s a little more to it, but it’s close enough.
But we’ll continue to talk about user sessions, not IP sessions. It’s simpler.
Suppose each user in Figure 5 – Louise, Jim, Clara, and Joe – connects to log-in.php. When log-in.php runs, it uses separate session data for each user:

Figure 7. log-in.php uses separate sessions
This means that each person’s log in data is kept separate.
Different users will run the same page, like log-in.php. But log-in.php will see different data for each user, because it is pulling data from each user’s own session memory.
Here’s an example. It isn’t accurate about how session data is stored; we’ll see that in a minute.

Figure 8. log-in.php uses different values for each user
log-in.php outputs $p. What will it show? Because the data comes from session memory, each user would see something different.
- Louise sees 17.
- Jim sees 23.
- Clara sees 29.
- Joe sees 31.
So the same code – print $p; – could show something different when it is run by different users, if it is using data from session memory.
Let’s look at the PHP statements that mess with sessions. We’ll only look at the core statements.
PHP’s session statements
Starting a session
You need to start the session mechanism before you can use it.
session_start();
This statement has to appear before the page outputs anything, or sessions won’t work.
Storing session data
Once a session has been started, you can store data into it using the $_SESSION array. For example:
$_SESSION['user name'] = 'jimmy';
The string between the quotes names the session data. Other examples:
$_SESSION['favorite number'] = 96;
$_SESSION['favorite color'] = 'green';
$_SESSION['database server'] = 'localhost';
Retrieving session data
You can retrieve session data as well. Again, you have to start the session first.
$user name = $_SESSION['user name'];
$num = $_SESSION['favorite number'];
$best_color = $_SESSION['favorite color'];
$db_server_host = $_SESSION['database server'];
Destroying a session
Destroy a session like this:
session_start();
$_SESSION = array();
session_destroy();
The second line erases the session data. The third one wipes out the session itself.
An example
Let’s look at a sample application that uses session. The user enters his/her name:

Figure 9. User enters name
The name is stored in the session.
The user then sees a menu, like this:

Figure 10. Menu
The user’s name is inserted into captions of photos. Here’s what clicking on the Renata link shows:

Figure 11. Renata
You can try the application, and download its files.
Here are the pages in the application:

Figure 12. Pages in the application
Here are the pieces:
ask-user-name.htmlshows the form that gets the user’s name.remember-name.phpstores the user’s name in the session.menu.phpshows the application’s menu.cc.php,kieran.php, andrenata.phpshow photos with the user’s name in the captions.new-name.phperases the user’s name from the session, and jumps back to the user name form.
Let’s look at the code.
Getting the user’s name
ask-user-name.html shows the form:

Figure 9 (again). User enters name
The form passes the data to remember-name.php, which stores the data into the session.
Here’s the code for remember-name.php:
<?php
//Get the name the user typed.
$user_name = $_POST['user_name'];
//Validate.
if ( $user_name == '' ) {
header('location:ask-user-name.html');
exit();
}
//Start session.
session_start();
//Store data in session.
$_SESSION['user name'] = $user_name;
//Go to the main menu.
header('location:menu.php');
?>
Figure 13. remember-name.php
remember-name.php doesn’t output anything for the user to see. It puts data into the session, for other pages to use.
Line 3 gets the value the user typed into the form. Lines 5 to 8 check whether the value is empty. If it is, the browser is told to jump back to ask-user-name.html.
Now to store the name into the session. Line 10 starts the session:
session_start();
PHP pages need to do this before they can use sessions.
Line 12 stores the user name into the session:
$_SESSION['user name'] = $user_name;
Line 14 jumps to the menu:
header('location:menu.php');
The menu
Here’s the code for menu.php.
<?php
//Do we know the user's name?
session_start();
$user_name = $_SESSION['user name'];
if ( $user_name == '' ) {
header('location:ask-user-name.html');
exit();
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Menu | Sessions Sample App</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Menu</h1>
<p>Name: <?php print $user_name; ?></p>
<ul>
<li><a href="cc.php">CC photo</a></li>
<li><a href="kieran.php">Kieran photo</a></li>
<li><a href="renata.php">Renata photo</a></li>
<li><a href="new-name.php">Use a different name</a></li>
</ul>
</body>
</html>
Figure 14. menu.php
Line 3 starts the session.
Line 4 gets some data from the session:
$user_name = $_SESSION['user name'];
Lines 5 to 8 checks that there is a name. If not, the browser is sent to ask-user-name.html.
How could $_SESSION['user name'] be empty? It was just set in remember-name.php, wasn’t it?
You’re right, remember-name.php sets
$_SESSION['user name'], and then it jumps to menu.php.
But that’s only one way the user can get to menu.php. There are other ways. For example, the user can type the page’s URL directly into the browser:

Figure 15. User types menu.php into the browser
This skips remember-name.php, so the session data isn’t set.
It’s best not to assume that the session data is there.
The menu shows the user name:

Figure 10 (again). Menu
Here’s line 17 from menu.php:
<p>Name: <?php print $user_name; ?></p>
Showing a photo
Here’s renata.php, that shows the user’s name in a photo caption:
<?php
//Do we know the user's name?
session_start();
$user_name = $_SESSION['user name'];
if ( $user_name == '' ) {
header('location:ask-user-name.html');
exit();
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Renata Photo | Sessions Sample App</title>
</head>
<body>
<div id="container">
<p><img src="renata.jpg" alt="CC"></p>
<h1 class="loves">Renata loves <?php print $user_name; ?></h1>
</div>
<p><a href="menu.php">< Menu</a></p>
</body>
</html>
Figure 16. renata.php
Line 3 starts the session. Line 4 gets the user’s name from the session:
$user_name = $_SESSION['user name'];
Lines 5 to 8 check whether there is a user name. If not, jump to ask-user-name.html.
Line 18 puts the user name into the photo caption:
<h1 class="loves">Renata loves <?php print $user_name; ?></h1>
Changing the user name
What if the user wants to change the name that shows in the captions? There’s a link for that in the main menu.

Figure 10 (again). Menu
The last link in the menu sends the browser to new-name.php. Here is the code:
<?php
session_start();
//Erase the session variables.
$_SESSION = array();
//Kill the session.
session_destroy();
header('location:ask-user-name.html');
?>
Figure 17. new-name.php
new-name.php erases the session data (line 4) and kills the session itself (line 6). Then it sends to browser back to the user name form.
Again, new-name.php doesn’t output anything itself. It does something to the session, and jumps to another page.
Session lifetime
You might be asking yourself:
Self, do sessions last forever?
Sessions are destroyed when:
- A PHP program runs
session_destroy(); - The browser is closed.
- The session expires.
Sessions expire if the browser does not access a page in the application within a certain amount of time. You can set the amount of time sessions last. The default is 20 minutes.
Exercise: Event list
The Dog Center is a meeting center that holds lectures, demonstrations, workshops, and other events. About dogs, of course.
The Center’s management want to put information kiosks at the doors. They’ll be PCs with touch screens, running a Web browser. People can use the kiosks to learn about the events at the Center that day.
Here’s what the kiosk’s screen will look like for a typical day:

Figure 1. Event list
Clicking on a link shows an event:

Figure 2. Event
There’s a joke at the bottom of every page. When a kiosk is started for the day, it asks the user for a joke:

Figure 3. Asking for a joke
The joke is stored in the session. It’s then shown on every page.
Management wants to be able to change the joke if need be. Add a link to the menu to do that. But the link should be hidden on the lower right of the page. The mouse cursor should change when passing over the link, but the link itself should not show:

Figure 4. Secret link
When the link is clicked, the browser asks for a joke again, as in Figure 3.
You can try my solution. You can also download the files, but do it yourself first!
Hint: what happens when color and background-color are the same?
Upload your solution to your hosting account. Put the URL below.
(Log in to enter your solution to this exercise.)
Summary
- Session memory is separate from any one page.
- Pages can store data in session memory, and retrieve it.
- Sessions can be destroyed by PHP pages. Sessions expire after a time of inactivity.
What now?
This chapter is about restricting access to pages on a Web site. You just saw how sessions let PHP pages share information. Now let’s talk about storing data about users and their permissions.