我正在创建一个 php 登录页面。当传递 $_SESSION 变量“success”时,我无法让页面重定向(在这种情况下为 index.php)。我可以让成功消息起作用,所以我认为我的表单和查询都很好。我在这里想念什么?
这是表单(login.php):
<? $page = "login-page";//body tag class
$title = "Log in to your Bloggr Account";//title tag text
session_start();
require_once('includes/header.php');
print_r($_SESSION); ?>
<p class="errors" id="errors">
<? if(!empty($_SESSION['errors'])){ ?>
<script type="text/javascript"> $(function() {
setTimeout(function(){
$("#errors").fadeIn(500);}, 500)});
<script>
<? foreach($_SESSION['errors'] as $error){
echo $error;}
session_unset($_SESSION['errors']);
} ?>
</p> <? if(!empty($_SESSION['success'])){
header("Location: index.php");
echo $success;
session_unset($_SESSION['success']); } ?>
<form action="login-post2.php" method="post" class="admin-form login">
<label for="userName">User Name <label>
<input type="text" name="userName" class="user-name" value="" />
<label for="password">Password</label>
<input type="password" name="password" class="password" />
<input type="submit" class="submit" name="register-submit" value="Log In!" />
</form>
这是发布文件(login-post2.php)
<? if($_SERVER["REQUEST_METHOD"] == "POST"){
session_start();
require_once('../_db_connect.php');
$errors = array();
$success = "You're logged in!";
if(empty($_POST['userName'])){
$errors[] = "Please enter a user name.";
}else[
$userName = $_POST["userName"];
}
if(empty($errors)){
$query = "SELECT userName, password FROM users WHERE userName = '$userName' and password = SHA1('$password')";
$result = mysqli_query($dbconnect, $query);
if(!result){
$errors[] = "Please try again!";
} else{
$success;
}
}
$_SESSION['errors'] = $errors;
$_SESSION['success'] = $success;
exit();
} ?>
抱歉,如果某些格式有点不对劲。
* 为将来遇到此问题的任何人编辑[已解决] ,这就是我所做的。这是我问题的最大部分:
if(empty($errors)){
$query = "SELECT userName, password FROM users WHERE userName = '$userName' and password = SHA1('$password')";
$result = mysqli_query($dbconnect, $query);
if(mysqli_num_rows($result) == 1){//if username and password match;
$row = mysqli_fetch_array($result);
$_SESSION['loggedIn'] = $loggedIn;
header("Location: index.php");
exit();
}
} else{
$_SESSION['errors'] = $errors;
header("Location: login.php");
exit();
}
我没有很好地为 $errors 格式化 if/else 语句。我当时知道但无法弄清楚的部分问题是我需要一种方法来发送两次标头。如果我有 $errors 和另一种方式,如果我没有。我以前的方式是尝试在没有条件的情况下发送两次。我的解决方案是将我的语句的最后一点包装为 else,如果有错误,我可以将用户发送回登录页面,如果他们成功登录,则可以将其发送到索引页面。就是这样。希望这对将来的其他人有所帮助。