PHP会话——模拟购物车的功能

时间:2021-05-21 23:17:55

1、php默认是不开启会话的,要使用会话用两种方法:(1)使用session_start();显示的开启会话。(2)在php.ini中找到如下的一行:找到session.auto_start = 0,将0设置为1.下面通过一个模拟购物车的程序来展示seeion的基本操作。

session1.php

 <?php
//session_start();
?>
<!DOCTYPE html>
<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_products']));
$_SESSION['products']=serialize($products);
}
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>
<label for = "form_products">Select some products:</label><br />
<select id="form_products" name="form_products[]" 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="Transportor">Transportor</option>
</select>
</p>
<button type="submit" name="submit" value="choose">Submit Form</button>
</form>
<p><a href="session2.php">go to content page</a> </p>
</body>
</html>

session2.php

 <!DOCTYPE html>
<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_products']));
$_SESSION['products']=serialize($products);
}
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>
<label for = "form_products">Select some products:</label><br />
<select id="form_products" name="form_products[]" 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="Transportor">Transportor</option>
</select>
</p>
<button type="submit" name="submit" value="choose">Submit Form</button>
</form>
<p><a href="session2.php">go to content page</a> </p>
</body>
</html>