You use the $_SESSION array to store data in a session. This array is a global variable just like $_POST, $_GET, and $_REQUEST. Note that you must start your session using session_start before you can use $_SESSION. Here's an example, where we'll use session_start and then store some data in the session under the name temperature, setting it to 72: <?php session_start(); $_SESSION['temperature'] = "72"; ?> After storing that data in a session, we'll let the user move to another page, phpsession2.php, before recovering that data, so we'll also include a hyperlink to phpsession2.php in phpsession.php, as you can see in Example 9-12. Example 9-12. Storing data in a session, phpsession.php<HTML> <HEAD><TITLE>Storing data in sessions</TITLE></HEAD> <BODY><CENTER> <H1> Storing data in sessions </H1> <?php session_start(); $_SESSION['temperature'] = "72"; ?> Stored the temperature as 72 degrees. <BR> To read the temperature in a new page, <a href="phpsession2.php"> click here</a>. </CENTER><BODY> </HTML> You can see this page at work in Figure 9-11, where we've stored the data in the session. Figure 9-11. Storing data.If the user navigates to phpsession2.php, Example 9-13, before the session expires, we'll be able to recover the stored data and display it. You can see the retrieved data displayed in phpsession2.php, Figure 9-12. Cool. Example 9-13. Retrieving data in a session, phpsession2.php<HTML> <HEAD> <TITLE> Retrieving data in sessions </TITLE> </HEAD> <BODY> <CENTER> <H1> Retrieving data in sessions </H1> <?php session_start(); if(isset($_SESSION["temperature"])){ echo "Welcome. The temperature is " . $_SESSION['temperature']; } ?> </CENTER> <BODY> </HTML> Figure 9-12. Retrieving data. |