php 更改 SESSION 变量值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6999049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change SESSION variable value
提问by William Orazi
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:
一段时间以来,我一直试图弄清楚这一点,这让我发疯了。基本上我有一个供美国和加拿大用户使用的表格。表格底部有一个供加拿大用户使用的链接,可将用户引导至 can-session.php,其中包含:
<?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'] . '');
?>
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.
基本上,如果他们点击链接,它会设置 $_SESSION['can'] = 1。现在还有另一个选项,如果他们点击那个链接,它会将他们带回这个页面,会话应该被销毁,一个新的值已设置(嗯,这就是它应该做的)。问题是,我已经打印出 $_SESSION['can'],并且在转到该页面后它仍然保留该旧值。有没有更好的方法来做到这一点,或者我的代码有什么问题?谢谢您的帮助。
回答by Dan Grossman
This is what you wrote:
这是你写的:
if (isset($_SESSION['can'])) {
session_start();
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
是读取与用户的PHPSESSID
cookie关联的会话文件并填充的函数$_SESSION
,因此您试图在数组具有任何值之前从数组中读取。
You need to call session_start
beforeyou check if $_SESSION['can']
has a value.
您需要session_start
在检查是否$_SESSION['can']
有值之前调用。
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'] . '');
?>
回答by Naftali aka Neal
Try this: (using only onesession_start()
)
试试这个:(只使用一个session_start()
)
<?php
session_start();
if (isset($_SESSION['can'])) {
$_SESSION['can'] = 2;
}
else {
$_SESSION['can'] = 1;
}
header('Location: '. $_SERVER['HTTP_REFERER'] . '');
?>
回答by Just Another Coder
You may want to include
你可能想包括
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
instead of just plain
而不是简单的
session_start();