目录

cookie禁用前后session处理的差异

目录

session在用户禁用cookie后就不能正常使用,而是每一次session都建立一个新的session文件。为了解决这一问题则需加入如下代码。

选择页面(MyHall.php)代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?php
	if(isset($_GET['PHPSESSID'])){
		session_id($_GET['PHPSESSID']);
	}
	session_start();
	$sid=session_id();
	
	//购物大厅
	echo "<h1>欢迎购买</h1>";
	echo "<a href='ShopProcess.php?bookid=sn001&bookname=天龙八部&PHPSESSID=$sid'>天龙八部</a><br/>";
	echo "<a href='ShopProcess.php?bookid=sn002&bookname=红楼梦&PHPSESSID=$sid'>红楼梦</a><br/>";
	echo "<a href='ShopProcess.php?bookid=sn003&bookname=西游记&PHPSESSID=$sid'>西游记</a><br/>";
	echo "<a href='ShopProcess.php?bookid=snoo4&bookname=聊斋&PHPSESSID=$sid'>聊斋</a><br/>";
	echo "<hr/>";
	echo "<a href='ShowCart.php?&PHPSESSID=$sid'>查看购买到的商品列表</a>";

处理页面(ShopProcess.php)代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?php
	if(isset($_GET['PHPSESSID'])){
		session_id($_GET['PHPSESSID']);
	}
	
	session_start();
	$sid=session_id();
	//接收传来的数据
	$bookid=$_GET['bookid'];
	$bookname=$_GET['bookname'];
	//保存到session中
	$_SESSION[$bookid]=$bookname;
	echo "<br/>购买成功";
	echo "<a href='MyHall.php?PHPSESSID=$sid'><br/>返回购物大厅</a>";

显示session页面(ShowCart.php)代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
	if(isset($_GET['PHPSESSID'])){
		session_id($_GET['PHPSESSID']);
	}
	session_start();
	echo "所选的商品为";
	foreach($_SESSION as $key=>$val){
		echo "<br/> 书号--$key 书名--$val";
	}
	

禁用cookie前:

选择页面(MyHall.php)代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php
	session_start();
	//$sid=session_id();
	//购物大厅
	echo "<h1>欢迎购买</h1>";
	echo "<a href='ShopProcess.php?bookid=sn001&bookname=天龙八部'>天龙八部</a><br/>";
	echo "<a href='ShopProcess.php?bookid=sn002&bookname=红楼梦'>红楼梦</a><br/>";
	echo "<a href='ShopProcess.php?bookid=sn003&bookname=西游记'>西游记</a><br/>";
	echo "<a href='ShopProcess.php?bookid=snoo4&bookname=聊斋'>聊斋</a><br/>";
	echo "<hr/>";
	echo "<a href='ShowCart.php'>查看购买到的商品列表</a>";
	

处理页面(ShopProcess.php)代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
	/*if(!empty($_GET['PHPSESSID'])){
		session_id($_GET['PHPSESSID']);
	}*/
	session_start();
	//接收传来的数据
	$bookid=$_GET['bookid'];
	$bookname=$_GET['bookname'];
	//保存到session中
	
	//$_SESSION[$bookid]=$bookname;
	echo "<br/>购买成功";
	echo "<a href='MyHall.php'><br/>返回购物大厅</a>";

显示session页面(ShowCart.php)代码:

1
2
3
4
5
6
7
8
9
<?php
	/*if(!empty($_GET['PHPSESSID'])){
		session_id($_GET['PHPSESSID']);
	}*/
	session_start();
	echo "所选的商品为";
	foreach($_SESSION as $key=>$val){
		echo "<br/> 书号--$key 书名--$val";
	}

原理:session中的sessionid传递需要cookie,

抓取http结果:

Set-Cookie: PHPSESSID=4rd8untdg7a83mp9c8vl4hn2c0; path=/

而禁用session后:

会建立多个PHPSESSID,最后导致找不到session文件,而无法完成session的功能。