PHP 会话变量未保存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18436946/
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
PHP Session variable is not saving
提问by puddleJumper
I've looked through all the problems about the session variable not saving and don't see my problem so I'm going to ask it.
我已经查看了有关会话变量未保存的所有问题,但没有看到我的问题,所以我要问它。
I have a form that once submitted it searches my database for that name. The initial form is on page 1. On page 2 I take the the variable from page 1 and save it like this
我有一个表单,一旦提交,它就会在我的数据库中搜索该名称。初始表单在第 1 页。在第 2 页,我从第 1 页获取变量并像这样保存
$searchTerm = $_POST['find'];
which is used as the search for the database and it works perfectly. Under that I have my sql statement then I have placed this
它用作数据库的搜索,它完美地工作。在那之下我有我的 sql 语句然后我把这个
//initialize the session
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['searchTerm'] = $searchTerm;
I have then tested the $_SESSION['searchTerm'] on page 2 to make sure that it is saving properly, and it does. My issue comes in when I try to go to a 3rd page that is a confirm page for the form from page 2. I have the session start clause at the top of the 3rd page and I even inserted
然后我测试了第 2 页上的 $_SESSION['searchTerm'] 以确保它正确保存,并且确实如此。当我尝试转到第 3 页时出现问题,该页是第 2 页表单的确认页。我在第 3 页的顶部有会话开始子句,我什至插入了
ini_set('display_errors',1);
error_reporting(E_ALL);
to check for errors, no errors were displayed. So my next step was to test the session itself to see if it was refreshing the session id. I found a script on this site www.webassist.com/forums/posts.php?id=5735 to test whether the server could possibly be causing the issue. The script works fine no problems, showing that the server is not the problem. However when I upload my 2nd and 3rd page to the server and put in
检查错误,没有显示错误。所以我的下一步是测试会话本身,看看它是否正在刷新会话 ID。我在这个网站 www.webassist.com/forums/posts.php?id=5735 上找到了一个脚本来测试服务器是否可能导致问题。脚本工作正常没有问题,表明服务器不是问题。但是,当我将第二页和第三页上传到服务器并放入时
<?php echo session_id(); ?>
the numbers from page 2 and page 3 are completely different therefore making my variable null. I did further research and thought it might be because there was a session_destroy or session_unset but I didn't put one of these on either page. When I tried this on my local machine I got the same session id but still the session variable I set was blank.
第 2 页和第 3 页的数字完全不同,因此使我的变量为空。我做了进一步的研究并认为这可能是因为有 session_destroy 或 session_unset 但我没有在任一页面上放置其中一个。当我在本地机器上尝试这个时,我得到了相同的会话 ID,但我设置的会话变量仍然是空白的。
Does anyone have any other ideas on how or why this would happen?
有没有人对如何或为什么会发生这种情况有任何其他想法?
**********edit *********************
** *** *****编辑** *** *** *** *** *** *** *
page 1 has this form
第 1 页有这种形式
<form name="search" method="post" action="page2.php">
<div>
<!-- Search-->
<label>Search by Last Name:</label>
<div>
<table width="100%">
<tr>
<td><input type="text" id="" name="find" placeholder=""></td>
<td><button id="submit" type="submit"><span>Search</span></button></td>
</tr>
</table>
</div>
</div>
</form>
page 2
第2页
$searchTerm = $_POST['find'];
if(!empty($searchTerm ) && ctype_alpha($searchTerm ))
{
$whereclause = "WHERE mytable.lastName = '".$searchTerm ."'";
}
else {
$whereclause = "";
}
// sql query is here this one searches it is long and just used the $whereclause above.
// second sql query that is only submitted if button from the form below is hit is here.
$insertGoTo = "confirmPage3.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'] ;
}
header(sprintf("Location: %s", $insertGoTo));
//initialize the session
if (session_id() == '') {
session_start();
}
$_SESSION['searchTerm'] = $searchTerm;
// then the form is listed below that with the rest of the html
page 3
第 3 页
<?php if(session_id() == '') session_start(); ?>
if(!empty($_SESSION['searchTerm']) && ctype_alpha($_SESSION['searchTerm']))
{
$whereclause = "WHERE myTable.lastName = '".$_SESSION['searchTerm'] ."'";
}
else {
$whereclause = "";
}
// More sql statement here for this one it is only selecting not updating or changing anything.
// Table below this that is used to hold the items retrieved from the database.
***********edit 2 and my fix**********
** *** *** ***编辑 2 和我的修复*** *** *** *
so after some back and for with a few of you, Aaron Gong suggested I start with a blank page and go from there. I did this and have finally diagnosed the issue. It was something that I hadn't thought of that I very well should have. I don't like using dreamweaver and now I remember why. When I originally created the page 2 I used dreamweavers insert code to insert my sql statement to do the updating. Well it placed in the code these lines of code.
因此,在与你们中的一些人一起回来之后,Aaron Gong 建议我从空白页开始,然后从那里开始。我这样做了,终于诊断出了这个问题。这是我没有想到的,我很应该拥有的东西。我不喜欢使用 Dreamweaver,现在我记得原因了。当我最初创建第 2 页时,我使用 Dreamweavers 插入代码插入我的 sql 语句来进行更新。好吧,它在代码中放置了这些代码行。
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
This will completely mess with you if you are trying to send the user to another page to confirm their entries. I commented it out and set the $editFormAction to my page and used that in the header string and viola that immediately fixed my issue. What I hadn't realized is when it was refreshing the page that it was emptying my $_POST variable and found that error finally through the empty pages suggest by Aaron.
如果您尝试将用户发送到另一个页面以确认他们的输入,这将完全弄乱您。我将其注释掉并将 $editFormAction 设置为我的页面,并在标题字符串和中提琴中使用它立即解决了我的问题。我没有意识到的是,当它刷新页面时,它正在清空我的 $_POST 变量,并最终通过 Aaron 建议的空页面发现了该错误。
Hope this helps someone else and I will never trust the code from dreamweaver again. I learned to code by hand and should know better but I was in a hurry and thought oh it won't harm it.
希望这对其他人有所帮助,我再也不会相信来自 Dreamweaver 的代码了。我学会了手工编码,应该知道得更好,但我很着急,想哦它不会伤害它。
Thanks again to all your suggestions.
再次感谢您的所有建议。
回答by Aaron Gong
Not sure what your 3rd page looks like but mine would be:
不确定你的第三页是什么样子,但我的是:
session_start(); // Use session variable on this page. This function must put on the top of page.
if( isset($_SESSION['i_am_in']) ) echo "logged in";
My Page 2:
我的第 2 页:
if ($login_ok) {
session_start(); // Create session & settings
$_SESSION['abc123'] = 'whatever';
header('Location: page3.php');
}
回答by Mitchell Layzell
Page 1 is good, Page 2 and Page 3 should look something like this
第 1 页很好,第 2 页和第 3 页应该是这样的
PAGE 2
第2页
//initialize the session and set are $_SESSION variable from the form data
session_start();
$_SESSION['searchTerm'] = $_POST['find'];
//set where condition and check if $_POST['find'] has a value
$whereclause = "";
if(isset($_POST['find'])) {
$whereclause = "WHERE mytable.lastName = '".$_POST['find']."'";
}
/*execute your statement note: data passed such as $_GET, $_POST, $_SESSION should never
be directly in your statement, use PDO to prepare and execute your statements to prevent
SQL injection*/
//then if you wanted to be redirected to page 3 use header after your statement has executed
header('Location:comfirmPage3.php');
PAGE 3
第 3 页
//initialize the session so we can access our $_SESSION variables
session_start();
//set where condition and check is $_SESSION['searchTerm'] has a value
$whereclause = "";
if(isset($_SESSION['searchTerm'])) {
$whereclause = "WHERE myTable.lastName = '".$_SESSION['searchTerm'] ."'";
}
//execute your statement
回答by Sam
make a call to the session_start()function.
调用session_start()函数。
session_start()
This call should be in every script that needs to utilise the session data. For example, if you have a script that creates a CAPTCHA image and needs to store the secret word for the session, you will need to put session_start() at the beginning of the script. If you have another script that takes the user input for the form and checks the secret word entered by the user against what you stored earlier, you will also need to put session_start() in that script.
这个调用应该在每个需要利用会话数据的脚本中。例如,如果您有一个创建 CAPTCHA 图像的脚本并需要存储会话的密码,则需要将 session_start() 放在脚本的开头。如果您有另一个脚本接受用户对表单的输入,并根据您之前存储的内容检查用户输入的密码,您还需要将 session_start() 放入该脚本中。
The function session_start() takes no parameters. It always returns TRUE, so you don't have to bother to check its return value. since session_start() sets a cookie via the HTTP cookie header, you must call it before you output anything from your script. It's best to simply call it at the beginning of your script.
函数session_start() 不带参数。它始终返回TRUE,因此您不必费心检查其返回值。由于 session_start() 通过 HTTP cookie 标头设置 cookie,因此您必须在从脚本输出任何内容之前调用它。最好在脚本的开头简单地调用它。
Ending Sessions
结束会话
session_destroy()is used to destroy the data associated with a session. However, this in itself does not clean up everything. For example, the session cookie is not unset. The $_SESSION array is also still available until your script ends.
session_destroy()用于销毁与会话关联的数据。然而,这本身并不能清理一切。例如,会话 cookie 未取消设置。$_SESSION 数组在脚本结束之前仍然可用。
To remove the cookie, manually delete it using the usual method one uses to delete a cookie in PHP. To get the name of the cookie to delete, call the session_name() function, which returns a string that is also the name of the cookie set by the PHP session handler.
要删除 cookie,请使用通常用于在 PHP 中删除 cookie 的方法手动删除它。要获取要删除的 cookie 的名称,请调用 session_name() 函数,该函数返回一个字符串,该字符串也是 PHP 会话处理程序设置的 cookie 的名称。
*example code for how you can clean up after a session can be found in the official PHP manual.
*有关如何在会话后进行清理的示例代码可以在官方 PHP 手册中找到。
回答by Dipesh Parmar
replace
代替
if (!isset($_SESSION)) {
session_start();
}
with
和
session_start();
because $_SESSION
is super global and its always available.
因为$_SESSION
是超级全球性的,并且始终可用。
OR
或者
Try checking for a specific $_SESSION
ex. $_SESSION['session']
rather than just a $_SESSION
.
尝试检查特定的$_SESSION
前任。$_SESSION['session']
而不仅仅是一个$_SESSION
.
回答by Tuxes3
if(session_id() == ''){
session_start();
}
since $_SESSION is always available.
因为 $_SESSION 始终可用。
回答by Buttle Butkus
session_start()
session_start()
That should be right at the top of your scripts. No if
statements to determine whether to start it or not.
那应该就在脚本的顶部。没有if
语句来确定是否启动它。
PAGE 2In the second script, you have header(sprintf("Location: %s", $insertGoTo));
before you have session_start()
. Your session would never start if the header location is changed.
第 2 页在第二个脚本中,header(sprintf("Location: %s", $insertGoTo));
您拥有session_start()
. 如果标题位置更改,您的会话将永远不会启动。
Put session_start()
at the top. Do not surround it with the if statement.
放在session_start()
最上面。不要用 if 语句包围它。
PAGE 3Also put session_start()
at the top of the third page, without any if statement. You are not understanding session usage. It's not like a regular function. You must start the session first on every page you want to use it. You can't check for the contents of a $_SESSION variable before you call session_start()
.
PAGE 3也放在session_start()
第三页的顶部,没有任何 if 语句。您不了解会话使用情况。它不像常规功能。您必须首先在要使用它的每个页面上启动会话。您无法在调用之前检查 $_SESSION 变量的内容session_start()
。
Let me know when you've done that and what the results are.
让我知道你什么时候这样做了,结果是什么。
回答by D3stroyah
I had the same exact problem since 10 minutes ago and no answer helped me. I'm giving you another possible answer (you solved your problem but other people might have not).
自 10 分钟前以来,我遇到了完全相同的问题,但没有任何答案对我有帮助。我给你另一个可能的答案(你解决了你的问题,但其他人可能没有)。
I had file1.php
opening a session and saving a session variable, file2.php
opening the session and retrieving that variable from $_SESSION
. It didn't work and I also had two different sessions from file1
and file2
. The reason was that file1.php
was saved as UTF-8 WITH BOM
I it saved again with Notepad++ as UTF-8 WITHOUT BOM
.
我file1.php
打开了一个会话并保存了一个会话变量,file2.php
打开了会话并从$_SESSION
. 它没有用,我也有来自file1
和 的两个不同的会话file2
。原因是它file1.php
被保存了,因为UTF-8 WITH BOM
我用 Notepad++ 再次将它保存为UTF-8 WITHOUT BOM
.
Now everything works perfectly. I'm sure many people will fall in this problem I couldn't even think of.
现在一切正常。我敢肯定很多人会陷入这个我什至无法想到的问题。