我的登录时遇到问题,当我第一次打开浏览器时,我需要做2次登录才能重定向到我的索引。之后我可以退出并登录,一切正常。
我的登录代码:
<?php
include "connect.php";
session_start();
if (isset($_POST['user_login'])) {
$state_on = 1;
$state_off = 0;
$user = $conn->prepare("SELECT * FROM users WHERE username=:name AND password=:pword AND state=:s");
$user->bindParam(":name", $_POST['username']);
$user->bindParam(":pword", $_POST['password']);
$user->bindParam(":s", $state_on);
$user->execute();
if ($user->rowCount() > 0) {
$row_user = $user->fetch(PDO::FETCH_ASSOC);
$user_id = $row_user['id_user'];
$user_session = $row_user['session_id'];
$user_lvl = $row_user['id_lvl'];
$update_session = $conn->prepare("UPDATE users SET session_id =:idsession WHERE id_user=:iduser");
$update_session->bindParam(":iduser", $user_id);
$update_session->bindParam(":idsession", session_id());
$update_session->execute();
$_SESSION['session_id'] = $user_session;
$_SESSION['id_user'] = $user_id;
$_SESSION['id_lvl'] = $user_lvl;
header("Location: index.php");
// echo 'login = SUCCESS!';
} else {
// echo 'login = FAIL!';
}
}
这是我在index中包含的session.php。 PHP
session_start();
include "connect.php";
$login_session = $_SESSION['session_id'];
$login_user = $_SESSION['id_user'];
$login_nvlseg_user = $_SESSION['id_lvl'];
if (!isset($login_session)) {
$conn = null;
header('Location: login.php');
}
try {
$session_sql = "SELECT * FROM users WHERE session_id=:session";
$stmt = $conn->prepare($session_sql);
$stmt->bindParam(":session", $login_session);
$stmt->execute();
if ($stmt->rowCount() == 0) {
session_unset();
$conn = null;
header('Location: login.php');
}
} catch (PDOException $e) {
//
echo "Error: " . $e->getMessage();
}
由于
答案 0 :(得分:1)
在检查$ _POST之前,您必须检查用户是否已登录。
在它面前会是这样的:
session_start();
if (isset($_SESSION['id_user']) {
// redirect
header("Location: index.php");
}
答案 1 :(得分:1)
您需要将session_start
放在脚本之上,如下所示:
<?php
# session_start() should be on top when you using sessions
session_start();
include "connect.php";
if (isset($_POST['user_login'])) {
$state_on = 1;
$state_off = 0;
$user = $conn->prepare("SELECT * FROM users WHERE username=:name AND password=:pword AND state=:s");
$user->bindParam(":name", $_POST['username']);
$user->bindParam(":pword", $_POST['password']);
$user->bindParam(":s", $state_on);
$user->execute();
if ($user->rowCount() > 0) {
$row_user = $user->fetch(PDO::FETCH_ASSOC);
$user_id = $row_user['id_user'];
$user_session = $row_user['session_id'];
$user_lvl = $row_user['id_lvl'];
$update_session = $conn->prepare("UPDATE users SET session_id =:idsession WHERE id_user=:iduser");
$update_session->bindParam(":iduser", $user_id);
$update_session->bindParam(":idsession", session_id());
$update_session->execute();
$_SESSION['session_id'] = $user_session;
$_SESSION['id_user'] = $user_id;
$_SESSION['id_lvl'] = $user_lvl;
header("Location: index.php");
// echo 'login = SUCCESS!';
} else {
// echo 'login = FAIL!';
}
}
我希望这能解决你的问题!