更改SESSION变量值 [英] Change SESSION variable value
问题描述
我已经尝试了好一阵子了,这真让我发疯.基本上,我有一个针对美国和加拿大用户的表格.表单底部为加拿大用户提供了一个链接,该链接将用户定向到can-sesssion.php,其中包含:
I've been attempting to figure this out for a little while now, and it's driving me nuts. Basically I have a form for US and Canadian users. There's a link at the bottom of the form for Canadian users, which directs users to can-sesssion.php, which contains:
<?php
if (isset($_SESSION['can'])) {
session_start();
session_destroy();
session_unset();
session_start();
$_SESSION['can'] = 2;
}
else {
session_start();
$_SESSION['can'] = 1;
}
header('Location: '. $_SERVER['HTTP_REFERER'] . '');
?>
基本上,如果他们单击链接,它会设置$ _SESSION ['can'] =1.现在还有另一个选择,如果他们单击该链接,它将带他们回到此页面,并且该会话应该被销毁并设置一个新值(嗯,这就是应该做的).问题是,我已经打印出$ _SESSION ['can'],并且在转到该页面后仍然保留了旧值.有没有更好的方法可以做到这一点,或者我的代码有问题吗?感谢您的帮助.
Basically, if they click on the link, it sets $_SESSION['can'] = 1. Now There's another option, and if they click that link, it takes them back to this page, and the session should be destroyed and a new value is set (well, that's what it's supposed to do). Problem is, I've printed out $_SESSION['can'], and it's still retaining that old value after going to that page. Is there a better way to do this, or is there something wrong w/ my code? Thanks for the help.
推荐答案
这是你写的:
if (isset($_SESSION['can'])) {
session_start();
session_start
是读取与用户PHPSESSID
cookie相关联的会话文件并填充$_SESSION
的函数,因此您尝试从数组中读取任何值之前.
session_start
is the function which reads the session file associated with the user's PHPSESSID
cookie and populates $_SESSION
, so you're trying to read from the array before it has any values.
您需要先调用session_start
,然后再检查$_SESSION['can']
是否具有值.
You need to call session_start
before you check if $_SESSION['can']
has a value.
您也不需要销毁和创建新会话来更改值.
You also do not need to destroy and create a new session just to change a value.
<?php
session_start();
if (isset($_SESSION['can'])) {
$_SESSION['can'] = 2;
} else {
$_SESSION['can'] = 1;
}
header('Location: '. $_SERVER['HTTP_REFERER'] . '');
?>
这篇关于更改SESSION变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!