PHP会话变量在表单提交后没有更新



我有两个文件,一个包含表单,另一个包含操作,如果字段为空,则操作将用户发送回表单。我知道我可以用"required"来表示在采取行动之前必须输入;然而,我应该这样做,我们检查他们是否输入了用户名。如果不显示错误消息,则存储为$_SESSION['error']。

还没有检查SQL数据库,我已经处理了那部分。

这是我的表单(login.php):

<?php   
session_start();
?>
<div id="login-form-wrap">
<h2>Login</h2>
<form id="login-form" method="post" action="action.php">
<p>
<input type="text" id="username" name="username" placeholder="Username">
</p>
<p>
<input type="password" id="password" name="password" placeholder="Password">
</p>
<p>
<input type="submit" id="login" name="login" value="Login">
</p>
</form>
<div id="create-account-wrap">
<p>Not a member? <a href="create.php">Create Account</a><p>
</div>
<?php
if(isset($_SESSION['error'])) { 
echo $_SESSION['error']; 
} else{ 
echo "No errors."; 
} 
?>
</div>

这里是action。php:

<?php 
if (isset($_POST['login'])){ 
// checking if they hit the submit/login button
if(empty($_POST['username'])){
$_SESSION['error'] = "Please enter a username."; 
//should change the session variable error, but doesn't;

header("location:../login.php");
//redirects to login.php, this part works fine.
} else {
// means they entered a username, I have tried to change the session variable here too 
// but it never changes.
$name = $_POST['username'];
header("location:../login.php");
}
}

您的action.php与上面相同,因为您还没有启动会话。

session_start();

在您的action.php文件中您没有启动会话。为了在PHP中访问会话值,您必须首先使用session_start();函数。

你必须在表单提交后销毁会话值

在else部分的表单提交之后使用这段代码,在这里你想要清除会话值并且在使用会话变量

之前,你必须在action.php文件中启动session
// destroy the session
session_destroy(); 

最新更新