10.1 Creating a Session Variable with PHP


You want to create a session variable by using PHP.

Technique

Use the session_register() function to register a session variable:

 <?php session_register('session_variable'); $session_variable = $session_variable ? $session_variable + 1 : 20; echo $session_variable; ?> 

Comments

In PHP, there are currently 3 types of variables , all with different scopes and purposes. The first type of variable and the one with the most limited scope is the local variable. A local variable is any variable that is within the scope of a function, and it lasts only for the time of the function. Consider the following:

 <?php srand((double)microtime() * 1000000); function get_number($num) {     $num *= rand();     return ($num); } $number1 = get_number(rand()); $number2 = get_number(5); $number3 = get_number(5); print "Number 1 is $number1\n<br>\n        Number 2 is $number2\n<br>\n        Number 3 is $number3\n<br>\n"; ?> 

In this example, the $ret variable is locally scoped; that is, its value is not accessible outside the scope of the get_number() function.

The next type of variable is a global variable, which is any variable that is declared outside of a class or function (or declared by the global statement or declared through the $ GLOBALS array). Global variables last for the duration of the script's execution.

The last type of variable added in PHP 4 is the session variable. Session variables can (in theory) last forever, unless you or the user explicitly deletes them. (They can be automatically deleted after a certain time by setting configuration options correctly.)

So, session variables are simply regular variables that are declared using the session_register() function. They can be of any PHP-supported type: arrays, strings, numbers , even objects. The behavior of session_register() depends on the value of the register_globals PHP configuration parameter. If register_globals is on, session_register('foo') will save a global variable $foo in the session store. If it's off, it will look inside $HTTP_SESSION_VARS[] array, so $HTTP_SESSION_VARS['foo' ] will be saved.

Keep these considerations in mind while you read the rest of this chapter. A list of the topics we'll discuss is

  • Saving session variables in databases

  • Maintaining browser sessions from page to page

  • Setting and getting session names

  • Unsetting session variables

  • Finding the path where a session ID is saved



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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