表单提交后,php会话被删除

时间:2016-07-26 12:29:01

标签: php mysql forms session

似乎,我无法为脚本添加密码保护:它应该允许使用pass登录并将表单中的数据提交给mysql。登录看起来很好,但如果我尝试按提交,它会返回登录页面。似乎,该会话被删除或覆盖,但不清楚,如何:

//login area
<?php 
$password = "test"; 
session_start();
$_SESSION['txtPassword']= $_POST['txtPassword'] ;
if ( $_SESSION['txtPassword']!=$password ) {
?>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> 
<p><label for="txtPassword">Password:</label> 
<br /><input type="text" title="Enter your password" name="txtPassword" /></p> 
<p><input type="submit" name="Submit" value="Login" /></p> 
</form> 
<?  
}
elseif (  $_SESSION['txtPassword']=$password ) { 
echo $_SESSION['txtPassword'] ; // tried to print password, result is correct:      test 

//my db connection, just in case:
include "config.php";
$connect = mysqli_connect(HOST, USER, PASSWORD, NAME);

// data which should be inserted to db
if 
(@$_POST['posted']=='1' $_POST['posted'])) {
 $sSQL = "UPDATE users SET user_login='".mysqli_real_escape_string($connect, $_POST['usern'])."',user_pass='".mysqli_real_escape_string($connect, dohashpw($_POST['passw']))."' WHERE ID=1";
mysqli_query($connect, $sSQL) or print(mysql_error());
print ' <div class="container"> <p class="pstype">Password updated! </p>';
...
 //input form 
 <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"><input   type="hidden" name="posted" value="1" />

 <div class="col-xs-3">
 <label for="ex2">New Username: </label> 
 <input type="text" class="form-control input-lg" name="usern" >
 </div>

 <div class="col-xs-3">
 <label for="ex2">New Password: </label> 
 <input type="password"  class="form-control input-lg" name="passw" >
 </div>

 <div class="col-xs-3">
 <input type="submit" value="Submit" onclick="<? mysqli_query ($connect, $sSQL);?>; ">
 </div>
 </form> 

我可以登录此页面,但是当我填写表单并单击“提交”时,我再次获得登录区域。如果echo $ _SESSION显示正确的结果,我认为它已经建立,但是在提交后数据会丢失。你能帮我找到我的错误吗?

2 个答案:

答案 0 :(得分:0)

你在这里分配而不是比较:

elseif (  $_SESSION['txtPassword']=$password ) { 

这是更好的

elseif (  $_SESSION['txtPassword']==$password ) { 
无论如何,这不是一个坏主意,密码不应存储在这样的会话变量中,并且一旦用户提交密码就必须对它们进行哈希处理,并且只在代码和数据库中操作和存储哈希密码

答案 1 :(得分:0)

<?php 
$password = "test"; 
session_start();
$_SESSION['txtPassword']= $_POST['txtPassword'] ;
if($_SESSION['txtPassword']!=$password ){
?>
   <form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ? >"> 
   <p><label for="txtPassword">Password:</label></p>
   </br>
   <p><input type="text" title="Enter your password" name="txtPassword"/> </p> 
   <p><input type="submit" name="Submit" value="Login"/></p> 
   </form> 

<?php  
}
else{ 
 echo $_SESSION['txtPassword'];
}
?>

我不明白为什么elseif代表?你已经在if条件里面检查哪两个都不相等?