php使用Cookie实现和用户会话的方法(2)

在每一个 PHP 文档中访问一个唯一的会话标识符只是会话功能的开始。当一个会话启动后,我们可以在超全局变量 $_SESSION 中存储任意多个变量,然后在任何支持会话的页面上访问它们。

下面程序向超全局变量 $_SESSION 添加了两个变量:

复制代码 代码如下:

<?php
session_start ();
$_SESSION [ "product1" ] = "Sonic Screwdriver" ;
$_SESSION [ "product2" ] = "HAL 2000" ;
echo "The products have been registered." ;
?>


在用户移动到一个新的页面之前,上面程序的神奇之处不会体现出来。下面的程序创建了一个单独的 PHP 脚本,这个脚本访问存储在超全局变量 $_SESSION 中的变量。

复制代码 代码如下:

<?php
session_start ();
echo "Your chosen products are:" ;
echo "<ul>" ;
echo "<li>" . $_SESSION [ "product1" ]. "</li>" ;
echo "<li>" . $_SESSION [ "product2" ]. "</li>" ;
echo "</ul>" ;
?>


下列程序清单创建一个表单,它允许一个用户来选择多个产品。我们可以使用会话变量来创建一个基本的购物车。
arraysession.php:

复制代码 代码如下:

<?php
session_start ();
?>
<html>
<head>
<title> Storing an array with a session </title>
</head>
<body>
<h1> Product Choice Page </h1>
<?php
if ( isset ( $_POST [ "form_products" ])){
    if (! empty ( $_SESSION [ "products" ])){
       $products = array_unique (
       array_merge ( unserialize ( $_SESSION [ "products" ]),
       $_POST [ "form_produces" ]));
    }
    else
    {
       $_SESSION [ "products" ] = serialize ( $_POST [ "form_products" ]);
    }
    echo "<p>Your products have been registered!</p>" ;
}
?>
<form method = "POST" action = " <?php echo $_SERVER [ "PHP_SELF" ]; ?> " >
<p><strong> Select some products: </strong><br>
<select name = "form_product[]" multiple = "multiple" size = "3" >
<option value = "Sonic Screwdriver" > Sonic Screwdriver </option>
<option value = "Hal 2000" > Hal 2000 </option>
<option value = "Tardis" > Tardis </option>
<option value = "ORAC" > ORAC </option>
<option value = "Transporter bracelet" > Transporter bracelet </option>
</select>
<p><input type = "submit" value = "choose" /></p>
</form>
<p><a href = "session1.php" > go to content page </a></p>
</body>
</html>


 
session1.php:

复制代码 代码如下:

<?php
/*
  * Created on 2011-1-19
  *
  * To change the template for this generated file go to
  * Window - Preferences - PHPeclipse - PHP - Code Templates
  */
  session_start ();
?>
<html>
<head>
<title> Accessing session variables </title>
</head>
<body>
<h1> Content Page </h1>
<?php
if ( isset ( $_SESSION [ "products" ])){
    echo "<strong>Your cart:</strong><ol>" ;
    foreach ( unserialize ( $_SESSION [ "products" ]) as $p ){
       echo "<li>" . $p . "</li>" ;
    }
    echo "</ol>" ;
}
?>
<p><a href = "arraysession.php" > return to product choice page </a></p>
</body>
</html>


6.在查询字符串中传递会话 ID

7.销毁会话和重置变量

8.在一个带有注册用户的环境中使用会话

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/126e379ec5118c881f51d32d4be47a25.html