Session Function Overview

Session Function Overview

Session functions provide a unique identifier to a user, which can then be used to store and acquire information linked to that ID. When a visitor accesses a session-enabled page, either a new identifier is allocated, or the user is reassociated with one that was already established in a previous visit. Any variables that have been associated with the session become available to your code through the $_SESSION superglobal.

ارایه درگاه پرداخت ePayBank.ir برای برنامه نویسان سایتهای اینترنتی انلاین ایرانی

با مراجعه به سایت  mortezasaheb.ir میتوانید بسته آموزش طراحی سایت را خریداری نمایید.

ارایه خدمات تبلیغاتی خرید و فروش بسته های آموزش کدنویسی و طراحی قالب در MyCityAd.ir

Session state is usually stored in a temporary file, although you can implement database storage using a function called session_set_save_handler(). The use of session_set_save_handler() and a discussion about other advanced session functionality are beyond the scope of this book, but you can find more information in the PHP Manual section for sessions for all items not discussed here.

Starting a Session
To work with a session, you need to explicitly start or resume that session unless you have changed your php.ini configuration file. By default, sessions do not start automatically. If you want to start a session this way, you will have to find the following line in your php.ini file and change the value from 0 to 1 (and restart the web server):

session.auto_start = 0

By changing the value of session.auto_start to 1, you ensure that a session is initiated for every PHP document. If you don’t change this setting, you need to call the session_start() function in each script.

After a session is started, you instantly have access to the user’s session ID via the session_id() function. The session_id() function allows you to either set or retrieve a session ID. Listing 12.2 starts a session and prints the session ID to the browser.

Listing 12.2. Starting or Resuming a Session
1: <?php
2: session_start();
3: echo “<p>Your session ID is “.session_id().”.</p>”;
4: ?>

When this script is run for the first time from a browser, a session ID is generated by the session_start() function call on line 2. If the script is later reloaded or revisited, the same session ID is allocated to the user. This action assumes that the user has cookies enabled. For example, when I run this script the first time, the output is

Your session ID is fa963e3e49186764b0218e82d050de7b.

When I reload the page, the output is still

Your session ID is fa963e3e49186764b0218e82d050de7b.

because I have cookies enabled and the session ID still exists.

Because start_session() attempts to set a cookie when initiating a session for the first time, it is imperative that you call this function before you output anything else at all to the browser. If you do not follow this rule, your session will not be set, and you will likely see warnings on your page.

Sessions remain current as long as the web browser is active. When the user restarts the browser, the cookie is no longer stored. You can change this behavior by altering the session.cookie_lifetime setting in your php.ini file. The default value is 0, but you can set an expiry period in seconds.

Working with Session Variables
Accessing a unique session identifier in each of your PHP documents is only the start of session functionality. When a session is started, you can store any number of variables in the $_SESSION superglobal and then access them on any session-enabled page.

Listing 12.3 adds two variables into the $_SESSION superglobal: product1 and product2 (lines 3 and 4).

Listing 12.3. Storing Variables in a Session
1: <?php
2: session_start();
3: $_SESSION[“product1”] = “Sonic Screwdriver”;
4: $_SESSION[“product2”] = “HAL 2000”;
5: echo “The products have been registered.”;
6: ?>

The magic in Listing 12.3 will not become apparent until the user moves to a new page. Listing 12.4 creates a separate PHP script that accesses the variables stored in the $_SESSION superglobal.

Listing 12.4. Accessing Stored Session Variables
1: <?php
2: session_start();
3: echo “Your chosen products are:”;
4: echo “<ul>”;
5: echo “<li>”.$_SESSION[“product1″].”</li>”;
6: echo “<li>”.$_SESSION[“product2″].”</li>”;
7: echo “</ul>”;
8: ?>

Figure 12.2 shows the output from Listing 12.4. As you can see, we have access to the $_SESSION[ “product1” ] and $_SESSION[ “product2” ] variables in an entirely new page.

Figure 12.2. Accessing stored session variables.

Although not a terribly interesting or useful example, the script does show how to access stored session variables. Behind the scenes, PHP writes information to a temporary file. You can find out where this file is being written on your system by using the session_save_path() function. This function optionally accepts a path to a directory and then writes all session files to it. If you pass it no arguments, it returns a string representing the current directory to which session files are saved. On my system,

echo session_save_path();

prints /tmp. A glance at my /tmp directory reveals a number of files with names like the following:

sess_fa963e3e49186764b0218e82d050de7b
sess_76cae8ac1231b11afa2c69935c11dd95
sess_bb50771a769c605ab77424d59c784ea0

Opening the file that matches the session ID I was allocated when I first ran Listing 12.2, I can see how the registered variables have been stored:

product1|s:17:”Sonic Screwdriver”;product2|s:8:”HAL 2000″;

When a value is placed in the $_SESSION superglobal, PHP writes the variable name and value to a file. This information can be read and the variables resurrected lateras you have already seen. After you add a variable to the $_SESSION superglobal, you can still change its value at any time during the execution of your script, but the altered value won’t be reflected in the global setting until you reassign the variable to the $_SESSION superglobal.

The example in Listing 12.3 demonstrates the process of adding variables to the $_SESSION superglobal. This example is not very flexible, however. Ideally, you should be able to register a varying number of values. You might want to let users pick products from a list, for example. In this case, you can use the serialize() function to store an array in your session.

Listing 12.5 creates a form that allows a user to choose multiple products. You will use the session variables to create a rudimentary shopping cart.

Listing 12.5. Adding an Array Variable to a Session Variable
1: <?php
2: session_start();
3: ?>
4: <html>
5: <head>
6: <title>Storing an array with a session</title>
7: </head>
8: <body>
9: <h1>Product Choice Page</h1>
10: <?php
11: if (isset($_POST[ “form_products” ])) {
12: if (!empty($_SESSION[ “products” ])) {
13: $products = array_unique(
14: array_merge(unserialize($_SESSION[ “products” ]),
15: $_POST[ “form_products” ]));
16: $_SESSION[“products”] = serialize($products);
17: } else {
18: $_SESSION[“products”] = serialize($_POST[ “form_products” ]);
19: }
20: echo “<p>Your products have been registered!</p>”;
21: }
22: ?>
23: <form method=”POST” action=”<?php echo $_SERVER[ “PHP_SELF” ]; ?>”>
24: <p><strong>Select some products:</strong><br>
25: <select name=”form_products[]” multiple=”multiple” size=”3″>
26: <option value=”Sonic Screwdriver”>Sonic Screwdriver</option>
27: <option value=”Hal 2000″>Hal 2000</option>
28: <option value=”Tardis”>Tardis</option>
29: <option value=”ORAC”>ORAC</option>
30: <option value=”Transporter bracelet”>Transporter bracelet</option>
31: </select>
32: <p><input type=”submit” value=”choose” /></p>
33: </form>
34: <p><a href=”session1.php”>go to content page</a></p>
35: </body>
36: </html>

We start or resume a session by calling session_start() on line 2. This call gives us access to any previously set session variables. We begin an HTML form on line 23 and, on line 25, create a SELECT element named form_products[], which contains OPTION elements for a number of products.

By the Way

Remember that HTML form elements that allow multiple selections should have square brackets appended to the value of their NAME arguments. This makes the user’s choices available in an array.

Within the block of PHP code beginning on line 10, we test for the presence of the $_POST[“form_products”] array (line 11). If the variable is present, we can assume that the form has been submitted and information has already been stored in the $_SESSION superglobal.

We then test for an array called $_SESSION[“products”] on line 12. If the array exists, it was populated on a previous visit to this script, so we merge it with the $_POST[“form_products”] array, extract the unique elements, and assign the result back to the $products array (lines 1315). We then add the $products array to the $_SESSION superglobal on line 16.

Line 34 contains a link to another script, which we will use to demonstrate our access to the products the user has chosen. We create this new script in Listing 12.6, but in the meantime you can save the code in Listing 12.5 as arraysession.php.

Listing 12.6. Accessing Session Variables
1: <?php
2: session_start();
3: ?>
4: <html>
5: <head>
6: <title>Accessing session variables</title>
7: </head>
8: <body>
9: <h1>Content Page</h1>
10: <?php
11: if (isset($_SESSION[“products”])) {
12: echo “<strong>Your cart:</strong><ol>”;
13: foreach (unserialize($_SESSION[“products”]) as $p) {
14: echo “<li>”.$p.”</li>;
15: }
16: echo “</ol>”;
17: }
18: ?>
19: <p><a href=”arraysession.php”>return to product choice page</a></p>
20: </body>
21: </html>

Moving on to Listing 12.6, we see how to access the items stored in the session created in arraysession.php.

Once again, we use session_start() to resume the session on line 2. We test for the presence of the $_SESSION[“products”] variable on line 11. If it exists, we unserialize it and loop through it on lines 1315, printing each of the user’s chosen items to the browser.

For a real shopping cart program, of course, you would keep product details in a database and test user input, rather than blindly store and present it, but Listings 12.5 and 12.6 demonstrate the ease with which you can use session functions to access array variables set in other pages.

Passing Session IDs in the Query String
So far you have relied on a cookie to save the session ID between script requests. On its own, this method is not the most reliable way of saving state because you cannot be sure that the browser will accept cookies. You can build in a failsafe, however, by passing the session ID from script to script embedded in a query string. PHP makes a name/value pair available in a constant named SID if a cookie value for a session ID cannot be found. You can add this string to any HTML links in session-enabled pages:

<a href=”page2.html?<?php echo SID; ?>”>Another page</a>

It will reach the browser as

<a href=”page2.html?PHPSESSID=08ecedf79fe34561fa82591401a01da1″>Another page</a>

The session ID passed in this way will automatically be recognized in the target page when session_start() is called, and you will have access to session variables in the usual way.

Destroying Sessions and Unsetting Variables
You can use session_destroy() to end a session, erasing all session variables. The session_destroy() function requires no arguments. You should have an established session for this function to work as expected. The following code fragment resumes a session and abruptly destroys it:

session_start();
session_destroy();

When you move on to other pages that work with a session, the session you have destroyed will not be available to them, forcing them to initiate new sessions of their own. Any registered variables will be lost.

The session_destroy() function does not instantly destroy registered variables, however. They remain accessible to the script in which session_destroy() is called (until it is reloaded). The following code fragment resumes or initiates a session and registers a variable called test, which we set to 5. Destroying the session does not destroy the registered variable.

session_start();
$_SESSION[“test”] = 5;
session_destroy();
echo $_SESSION[“test”]; // prints 5

To remove all registered variables from a session, you simply unset the variable:

session_start();
$_SESSION[“test”] = 5;
session_destroy();
unset($_SESSION[“test”]);
echo $_SESSION[“test”]; // prints nothing.

Using Sessions in an Environment with Registered Users

The examples you’ve seen so far have gotten your feet wet with sessions, but perhaps additional explanation is warranted for using sessions “in the wild,” so to speak. The next few sections outline some examples of common session usage.

Working with Registered Users

Suppose that you’ve created an online community, or a portal, or some other type of application that users can “join.” The process usually involves a registration form, where the user creates a username and password and completes an identification profile. From that point forward, each time a registered user logs in to the system, you can grab the user’s identification information and store it in the user’s session.

The items you decide to store in the user’s session should be those items you can imagine using quite a bitand that would be inefficient to continually extract from the database. For example, suppose that you have created a portal in which users are assigned a certain level, such as administrator, registered user, anonymous guest, and so forth. Within your display modules, you would always want to check to verify that the user accessing the module has the proper permissions to do so. Thus, “user level” would be an example of a value stored in the user’s session, so that the authentication script used in the display of the requested module only has to check a session variablethere would be no need to connect to, select, and query the database.

Working with User Preferences

If you were feeling adventurous in the design phase of a user-based application, you might have built a system in which registered users could set specific preferences that would affect the way they viewed your site. For example, you may allow your users to select from a predetermined color scheme, font type and size, and so forth. Or, you may allow users to turn “off” (or “on”) the visibility of certain content groupings.

Each of those functional elements could be stored in a session. When the user logs in, the application would load all relevant values into the user’s session and would react accordingly for each subsequently requested page. Should the user decide to change her preferences, she could do so while logged inyou could even prepopulate a “preferences” form based on the items stored in the session rather than going back to the database to retrieve them. If the user changes any preferences while she is logged in, simply replace the value stored in the $_SESSION superglobal with the new selection no need to force the user to log out and then log back in again.