Примеры
Содержание
Замечание: As of PHP 4.1.0, $_SESSION is available as a global variable just like $_POST, $_GET, $_REQUEST and so on. Unlike $HTTP_SESSION_VARS, $_SESSION is always global. Therefore, you do not need to use the global keyword for $_SESSION. Please note that this documentation has been changed to use $_SESSION everywhere. You can substitute $HTTP_SESSION_VARS for $_SESSION, if you prefer the former. Also note that you must start your session using session_start() before use of $_SESSION becomes available.
The keys in the $_SESSION associative array are subject to the same limitations as regular variable names in PHP, i.e. they cannot start with a number and must start with a letter or underscore. For more details see the section on variables in this manual.
If register_globals is disabled, only members of the global associative array $_SESSION can be registered as session variables. The restored session variables will only be available in the array $_SESSION.
Use of $_SESSION (or $HTTP_SESSION_VARS with PHP 4.0.6 or less) is recommended for improved security and code readability. With $_SESSION, there is no need to use the session_register(), session_unregister(), session_is_registered() functions. Session variables are accessible like any other variables.
Пример #1 Registering a variable with $_SESSION.
<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
Пример #2 Unregistering a variable with $_SESSION and register_globals disabled.
<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
unset($_SESSION['count']);
?>
Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.
You can't use references in session variables as there is no feasible way to restore a reference to another variable.
If register_globals is enabled, then each global variable can be registered as session variable. Upon a restart of a session, these variables will be restored to corresponding global variables. Since PHP must know which global variables are registered as session variables, users need to register variables with session_register() function. You can avoid this by simply setting entries in $_SESSION.
Before PHP 4.3.0, if you are using $_SESSION and you have disabled register_globals, don't use session_register(), session_is_registered() or session_unregister(). Disabling register_globals is recommended for both security and performance reasons.
If register_globals is enabled, then the global variables and the $_SESSION entries will automatically reference the same values which were registered in the prior session instance. However, if the variable is registered by $_SESSION then the global variable is available since the next request.
There is a defect in PHP 4.2.3 and earlier. If you register a new session variable by using session_register(), the entry in the global scope and the $_SESSION entry will not reference the same value until the next session_start(). I.e. a modification to the newly registered global variable will not be reflected by the $_SESSION entry. This has been corrected in PHP 4.3.0.
Коментарии
I have wrote this following piece of code that shows how to work with global sessions (global to all clients) and private sessions (private per browser instance i.e. session cookie).
This code is usefull to store some read-only complex configuration and store it once (per server) and save the performance penatly for doing the same thing over each new private session...
Enjoy:
<?php
// Get the private context
session_name('Private');
session_start();
$private_id = session_id();
$b = $_SESSION['pr_key'];
session_write_close();
// Get the global context
session_name('Global');
session_id('TEST');
session_start();
$a = $_SESSION['key'];
session_write_close();
// Work & modify the global & private context (be ware of changing the global context!)
?>
<html>
<body>
<h1>Test 2: Global Count is: <?=++$a?></h1>
<h1>Test 2: Your Count is: <?=++$b?></h1>
<h1>Private ID is <?=$private_id?></h1>
<h1>Gloabl ID is <?=session_id()?></h1>
<pre>
<?php print_r($_SESSION); ?>
</pre>
</body>
</html>
<?php
// Store it back
session_name('Private');
session_id($private_id);
session_start();
$_SESSION['pr_key'] = $b;
session_write_close();
session_name('Global');
session_id('TEST');
session_start();
$_SESSION['key']=$a;
session_write_close();
?>
[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (lveillette AT silexmultimedia DOT com) on 19-NOV-09.]
It took me a while to find out how to use PHP sessions to prevent HTML form re-submits. A user can re-submit a form via the backspace key/back arrow and/or the F5/refresh key. I needed to control if/when a HTML form could be resubmitted. Here's what I came up with:
<?php
$SID = session_id();
if(empty($SID)) session_start() or exit(basename(__FILE__).'(): Could not start session');
$_SESSION['err'] = ''; $exit = false;
do {
// check if form was previously submitted
if(isset($_POST['submit']) and isset($_POST['SID']) and ($_POST['SID'] !== session_id())) {
$ret = null; $exit = true; break; }
// break out of do-while if form has not been submitted yet
if(empty($_POST['submit'])) break;
// process form data if user hit form "submit" button
if(isset($_POST['submit'])) {
$ret = validate_form();
// ret will be error message if form validation failed
if(is_string($ret)) { $_SESSION['err'] = $ret; break; }
// ret will be array of cleaned form values if validation passed
if(is_array($ret)) { session_regenerate_id(true); $exit = true; break; }
}
} while(false);
if($exit) display_receipt($ret);
$exit and exit;
function validate_form() {
$tmp = htmlspecialchars(strtoupper($_POST['name'])); // clean POST data
if(stripos($_POST['great'], 'yes') !== false) return array('name' => $tmp, 'great' => 'YES!');
return 'Wrong answer!';
}
function display_receipt($msg) {
if($msg === null) echo 'You already answered the question!';
if(is_array($msg)) echo 'Your answer of '.$msg['great'].' is right '.$msg['name'];
return;
}
?>
<html><body>
<?php echo $_SESSION['err']; ?>
<form name="form1" action="http://<?php echo $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF']; ?>" method="post">
Name: <input type="text" name="name" value="<?php isset($_SESSION["name"]) and print $_SESSION["name"]; ?>">
Is PHP great? <input type="text" name="great" value="<?php isset($_SESSION["great"]) and print $_SESSION["great"]; ?>">
<input type="hidden" name="SID" value="<?php echo session_id(); ?>">
<input type="submit" name="submit" value="Submit">
</form></body></html>
To avoid re-submits I add a random-number $rand to the form by "GET".
(action='file.php?rand= $rand').
Further, the $rand is stored in a SESSION-variable.
Everytime the file ist called, the functions will only be processed if the $rand that comes by "GET" is not identical to the $rand in the SESSION-variable.
If someone comes there by pressing the "back" key of his browser, the 2 $rand will be identical and nothing will happen.
That works perfect.
Another option that prevents form resubmit using the back button, and one that does not require sessions or predefined get parameters, is redirecting to a different url after the form is submitted.