Here's an example that points out the advantages of using sessions. Say you want to create a hit counter that keeps track of the number of times a user has visited a specific page. If you try to simply increment a variable, $counter, as shown in phpcounter.php, Example 9-14, there will be a problem because the data in that variable is not preserved between page accesses. Example 9-14. Hit counter first try, phpcounter.php<HTML> <HEAD> <TITLE> A hit counter </TITLE> </HEAD> <BODY> <CENTER> <H1> A hit counter </H1> Welcome. You've been here <?php $count++; echo $count ; ?> times before. </CENTER> <BODY> </HTML> As shown in Figure 9-13, no matter how many times you load the page, the counter will always be reset (and you'll get a notice about incrementing an undefined variable). Figure 9-13. First attempt at a hit counter.The solution is to store the count in a session, as you see in Example 9-15. Example 9-15. Corrected hit counter, phpcounter.php<HTML> <HEAD> <TITLE> A hit counter </TITLE> </HEAD> <BODY> <CENTER> <H1> A hit counter </H1> Welcome. You've been here <?php session_start(); if (!isset($_SESSION['count'])) { $_SESSION['count'] = 0; } else { $_SESSION['count']++; } echo $_SESSION['count']; ?> times before. </CENTER> <BODY> </HTML> You can see the final working version in Figure 9-14. Nice. Figure 9-14. The working hit counter. |