Starting a Session

   

You cannot track variables across a user session unless you start the session on each page on which you want to use or alter those variables. Starting a session uses the session_start() function:

 session_start();  

session_start() takes no arguments. If you are starting a new session, then the function initializes the session and creates the necessary temp files to track the session. If a $PHPSESSID is found by the function, either by a cookie or a GET variable, then the function resumes the current session and the page has access to any variables that have been registered to the session.

Once you have started the session, you need to register some variables with it. The session will not track variables until they have been registered using the session_register() function:

 session_register(STRING);  

The STRING argument to session_register() should be the name of the variable that you want to register with the session so that it may be accessed across any session-enabled pages.

Once you have started the session and registered one or more variables, you can use those variables across any session enabled pages on your site. Script 2-1, session.php, provides a simple example of starting a session and registering a variable.

Script 2-1 session.php
  1.  <?  2.  session_start();  3.  if(!isset($count)) {  4.    session_register("count");  5.    $count = 1;  6.  }  7.  ?>  8.  You have been to this page <?=$count?> times.  9.  <? 10.  $count++; 11.  ?> 

Script 2-1. session.php Line-by-Line Explanation

LINE

DESCRIPTION

2

Start the session or continue an existing session.

3

The if statement checks to see if the $count variable has been set. If the $count variable has been set, then the script assumes that this is a continuation of a session and takes no action and the script continues onto line 7.

4

If the $count variable has not been set, then the script assumes that this is the beginning of a new session and registers the variable $count.

5

Since the script has just registered the variable $count in the preceding line, it uses this line to assign a default value of 1 to $count.

8

Display a line of text stating the number of times the page has been viewed.

10

Increment the $count variable by one.

Run this script and click the reload button several times. Notice that the number of times the page has been viewed increases by one each time you reload the page. Figure 2-1 shows an example of this. Closing the browser then reloading the page in a new browser resets the $count to '1', as closing the browser effectively ends the session.

Figure 2-1. session.php

graphics/02fig01.jpg


   
Top


Advanced PHP for Web Professionals
Advanced PHP for Web Professionals
ISBN: 0130085391
EAN: 2147483647
Year: 2005
Pages: 92

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net