Tracking Visitors with Sessions - PHP - PHP, MySQL, JavaScript & HTML5 All-in-One For Dummies (2013)

PHP, MySQL, JavaScript & HTML5 All-in-One For Dummies (2013)

Book IV: PHP

Chapter 6: Tracking Visitors with Sessions

In This Chapter

arrow.png Understanding sessions and cookies

arrow.png Using sessions

This chapter looks at PHP’s built-in method for keeping track of visitors across multiple pages, called a session. The chapter starts out with an introduction to sessions and cookies and then jumps straight in by showing you how to use sessions to track visitors.

Understanding Sessions and Cookies

You’ve undoubtedly seen websites that track who you are, possibly welcoming you after you log in or presenting you with custom information about your account after logging in. There are a couple ways to do this, including sending the data along in a form with every request. But that isn’t secure and isn’t nearly flexible enough for today’s web applications. Luckily, there’s a better way — and it’s right at your fingertips: sessions.

Looking at sessions

A session in PHP is a secure way to track a user from page to page. With a session, you can store information about users, such as their e-mail address, name, phone number, and whatever other details you have, and automatically fill in that information wherever it’s needed on the site. For example, say that on login you load the user’s first name and e-mail address from your user database. You can store that information in a session, essentially hidden from the user, until you use it.

You use session variables as you would any other variables. Behind the scenes, sessions are stored in an array called $_SESSION. You store values just as you would with a named array in PHP. For example, you can keep track of an e-mail address and name like this:

$_SESSION['emailAddress'] = "me@example.com";

$_SESSION['firstName'] = "Steve";

You can also use sessions to keep track of information filled in on a web form without having to carry that information through the site in hidden form variables.

Working with cookies

Sessions are passed in browser cookies, which are little extra bits of information that get sent to and from a web browser. The actual bits of information, or what those bits actually are, is up to you, the programmer. For instance, you could send a cookie that contains the user’s name. The cookie could then be stored on the user’s computer and the next time she visits the site, the cookie would be sent to your program, which would then present a personalized greeting.

However, cookies are like any other data that you get from a user — the data from cookies needs to be sanitized (as we discuss in the preceding chapter) because it can’t be trusted. In other words, once your program sends a cookie to a visitor’s browser, the visitor can edit or change that cookie to be anything he wants. So if you (the web developer) are using the cookie to store a username, the visitor can change the username to whatever he wants and then send it back to your program.

The possibility of users editing their cookies is largely solved by simply using sessions. When a session cookie is created, it uses a hash value, which is a long string of characters. This means that even if users change the cookie value, in other words, if they change that hash, they aren’t really changing anything that you’re using in your program directly.

Instead, PHP handles the translation of that hash from the cookie on your behalf, and then you can get on with the business of using things in the $_SESSION array, as explained earlier. The actual values that you store in the $_SESSION array are never seen by the user; they exist only on the server.

Of course, using sessions with cookies means that cookies need to be enabled in the user’s browser. If they aren’t, then the user can’t use the application. Therefore, the logical place to continue this discussion is by showing how to check if cookies are enabled.

Checking if cookies are enabled

You use the setcookie() function in PHP to set a cookie in the browser. Then if your program can read that cookie, you know that cookies are enabled. The setcookie() function accepts several arguments to define the behavior of the cookie. For example, you set the name of the cookie, but you can also set how long the cookie will be active and whether it will be used over secure connections only, along with several other options.

For our purposes, we simply set the name of the cookie and a value. You can follow these steps to check if cookies are enabled in your browser.

1. Open your text editor and create a new empty file.

2. Within the file, enter the following code:

<?php

if (isset($_GET['cookiecheck'])) {

if (isset($_COOKIE['testcookie'])) {

print "Cookies are enabled";

} else {

print "Cookies are not enabled";

}

} else {

setcookie('testcookie', "testvalue");

die(header("Location: " . $_SERVER['PHP_SELF'] . "?cookiecheck=1"));

}

?>

3. Save the file as cookie.php in your document root.

4. Point your web browser toward http://localhost/cookie.php and you'll see a page like the one in Figure 6-1.

9781118213704-fg040601.eps

Figure 6-1: Checking if cookies are enabled.

If cookies aren’t enabled in your browser, you’ll see a page like that in Figure 6-2.

9781118213704-fg040602.eps

Figure 6-2: Showing that cookies are not enabled.

Note: If you'd like to test the page with cookies disabled, you can do so. First, close the browser and then reopen it (without going to the cookie.php page). In Internet Explorer, go to Internet Options. On the Privacy tab, slide the Settings slider up to block all cookies. In Firefox, go to Options, and select the Privacy tab. Within the History section, select Use custom settings for history and then uncheck the "Accept cookies from sites" check box. Now load the cookie.php page.

Now that you know that cookies are enabled you can safely begin to use sessions.

Using Sessions to Pass Data

With cookies enabled, which they usually are in most browsers, you can begin to use sessions to store data between pages of your PHP application.

Starting a session

The key to using sessions is the session_start() function. You call session_start() on every page and subsequently have access to all the items in the $_SESSION array.

It might seem like a bit of an odd name for the function, session_start(), because on most pages you really just want to continue the session and access the variables that are there. But in reality, session_start() does both: It starts a new session if need be and continues an existing session where appropriate.

The session_start() function is called simply like this:

<?php

session_start();

// Other PHP statements here

?>

Here's code for a few pages that track when you accessed the first page of the application. This shows the use of the session_start() function and then creation of a variable to hold the initial access time.

Listing 6-1 shows the code for the first page, called page1.php.

Listing 6-1: Creating a Session Variable

<?php

session_start();

$_SESSION['accessTime'] = date("M/d/Y g:i:sa");

print "This is page 1<br />";

print "You accessed the application at: " . $_SESSION['accessTime'];

print "<div><a href=\"page2.php\">Continue to next page</a></div>";

?>

When viewed in a browser, the page looks like Figure 6-3.

9781118213704-fg040603.eps

Figure 6-3: Accessing the first page of the application.

The next page in the application then starts the session and can access any variables already set in the session. Listing 6-2 shows code for the second page, page2.php.

Listing 6-2: The Second Page Accessing Session Variables

<?php

session_start();

print "This is page 2<br />";

print "You accessed the application at: " . $_SESSION['accessTime'];

print "<div><a href=\"page3.php\">Continue to next page</a></div>";

?>

Notice in the code in Listing 6-2 that the variable $_SESSION['accessTime'] is not set again, but merely accessed after the session is started. When you're on page1.php and click the link to go to the next page, you get a page like that in Figure 6-4.

9781118213704-fg040604.eps

Figure 6-4: Accessing the second page of the application.

You can store just about anything in a session, but you should be aware that session can, and sometimes does, disappear for a variety of reasons. One reason a session might disappear is that it times out. If users sit on a page for too long, the session might not be there when they begin using the application again.

In Book VII, you see how to change the session timeout value. However, even if you change the session timeout, the session can still go away. For example, if users clear their cookies in the middle of a session, then the session cookie will disappear and a new one will be started.

The practical implication of session disappearance is that any variables you've previously set will also disappear. Therefore, it's good practice to check if the session contains the values that you expect prior to using them. There are a couple ways to do this. One way would be to check all variables prior to accessing them. For example, you could change Listing 6-2 to check for the $_SESSION['accessTime'] variable prior to using it in output. Listing 6-3 shows what that would look like.

Listing 6-3: Checking if a Session Variable is Set before Using It

<?php

session_start();

if (!isset($_SESSION['accessTime'])) {

die(header("Location: page1.php"));

}

print "This is page 2<br />";

print "You accessed the application at: " . $_SESSION['accessTime'];

print "<div><a href=\"page3.php\">Continue to next page</a></div>";

?>

Listing 6-3 added the following code:

if (!isset($_SESSION['accessTime'])) {

die(header("Location: page1.php"));

}

remember.eps The location of that code is important. Because that code needs to send an HTTP header, it needs to appear prior to any other output. So for instance, if that code appeared below the "This is page 2" output, it wouldn't work because the headers have already been sent. The code appears prior to any output but also importantly, appears after the session_start() function.

Best practice is to check for the existence of session variables before you use them, as just shown. However, it can get quite cumbersome to check all the variables that you might use in a big application. With that in mind, another option is to set a global session variable and check for its existence rather than each variable individually. Here’s how to do that.

Listing 6-4 shows an updated version of the Listing 6-1, page1.php. In this code, there's a single addition, a new session variable called appStarted.

Listing 6-4: Adding a Global Variable for Session

<?php

session_start();

$_SESSION['appStarted'] = true;

$_SESSION['accessTime'] = date("M/d/Y g:i:sa");

print "This is page 1<br />";

print "You accessed the application at: " . $_SESSION['accessTime'];

print "<div><a href=\"page2.php\">Continue to next page</a></div>";

?>

You can then change other pages in the application to check for the existence of this variable, as in the change noted in Listing 6-5.

Listing 6-5: Checking for the Global Session Variable

<?php

session_start();

if (!isset($_SESSION['appStarted'])) {

die(header("Location: page1.php"));

}

print "This is page 2<br />";

print "You accessed the application at: " . $_SESSION['accessTime'];

print "<div><a href=\"page3.php\">Continue to next page</a></div>";

?>

Closing a session

Now you know how to start a session, but how do sessions get closed? The long and short of it is that sessions close at the end of the PHP program. This means that you don’t need to do anything explicit in order to close sessions.

Using session_write_close()

There are certain situations where you do in fact need to explicitly close the session. This might be the case if two programs or two sections of a program need to write to the session at the same time — or if you're using a redirect and the server doesn't quite get the session closed in time before the next page tries to pick up the session. In either case, the session_write_close() function will write the session parameters to the server and close or end the session. You call session_write_close() just like session_start();

session_write_close();

Any attempt to write a session variable after session_write_close() has been called may result in an error or may fail silently, depending on your PHP configuration.

Understanding Other Session Options

Several options are available when working with sessions in PHP, many of which you’ll never encounter and others that you’ll encounter in special situations. Table 6-1 lists some of the options.

Table 6-1 Selecting Session Options

Option

Description

session_id

Obtain the current session identifier or set one.

session_name

Obtain the current session name or set one.

session_destroy

Unset all variables from the current session.

Book VI shows the use of session_destroy in order to provide logout functionality on a website.

You can read about other session-related functions on the PHP website at www.php.net/manual/book.session.php.