1:我使用register.php注册客户端,
2:从表单收集的数据发送到1.php,保存在数据库中
3:表格数据保存在数据库后,1.php将选定的表格数据(myValue)转发给register.php?myValue ='abc'
在1.php中,我正在保存像这样的会话变量
@session_start();
$_SESSION['color']='blue';
register.php的代码是
if (isset($_SESSION['color'])) {
header('Location: http://mydomain.com/thankyou.php');
}
else {
@session_start();
some other stuff that was initially use for signing up the clients
我的逻辑是检查会话变量并将其重定向到某个其他页面
当步骤1,步骤2和步骤3完成时,页面应该是 重定向到thankyou.php
目前,当完成第1步,第2步,第3步,而不是打开thankyou.php时,正在打开以下页面
http://mydomain.com/register.php?myValue='abc'
但是,如果我重新打开register.php或者回到第一步(打开register.php),会显示thankyou.php ...
有人可以指导我在哪里犯错误吗?尽管创建了会话变量,为什么重定向不成功?
代码更新
我在register.php
的顶部尝试了以下代码@session_start();
if (isset($_SESSION['color'])) {
header('Location:http://mydomain.com/thankyou.php');
exit;
}
else{
remaining stuff
它偶尔会发挥作用,重定向到页面,有时(数量更多),它无法重定向到thankyou.php,代码也需要删除完整的历史记录和缓存才能工作(这样做之后,仍然错过点击发生..)
答案 0 :(得分:3)
在register.php中,在发出session_start之前无法测试会话变量,因此您的代码应该更像:
session_start();
if (isset($_SESSION['color'])) {
header('Location: http://mydomain.com/thankyou.php');
}
else {
// Something else....
编辑:
在尝试将会话变量与重定向结合使用时,我发现有用的另一件事是仅在运行函数后才进行重定向。以下是它的工作原理:
$throwAwayVariable = setColor('blue');
if($throwAwayVariable ){ // separated out into a function so it wouldn't redirect before the session variable was saved
session_write_close();
header("Location: http://mydomain.com/thankyou.php");
}
function setColor($color){
@session_start();
$_SESSION['color']='blue';
return true;
}
由于并非所有代码都已过帐,因此您必须弄清楚这是怎么回事,但我总是让我的会话变量在此过程之后工作。
答案 1 :(得分:3)
确保使用exit(0);在你执行标题重定向之后,否则php仍会解析并运行脚本的其余部分,有时它会导致一些有趣的行为。
答案 2 :(得分:2)
您在register.php中的session_start()
调用需要在调用任何$_SESSION
变量之前。
答案 3 :(得分:0)
我遇到同样的问题,然后我尝试添加session_start
和session_write_close
,这样就行了!
session_start();
$_SESSION['status'] = 'Updated Poem successfully';
session_write_close();
header("location: index.php");