我已经检查了正常的东西,比如 php 标签之前的空格,并且有一个 session_start(),但无法解决这个问题。我正在为客户制作登录系统,所以这是至关重要的东西。
基本上,一旦我到达第二页,$_SESSION['用户名];是空的。我已经打印出来了,它是空的,但是atm激活了您可以在代码中看到的标头重定向。
提前感谢您收到的任何帮助:)
相关代码:
<?php
session_start();
include '../resources/methods/Library.php';
if(isset($_SESSION['username']))
{
//User already logged in!
header('Location: Index.php');
}
//Username and password submitted by user
$usernameSubmitted = $_POST['username'];
$passwordSubmitted = $_POST['password'];
if($usernameSubmitted != "" && $passwordSubmitted != "")
{
//User has entered both a username and a password. We shall validate them
//Connect to database and select all the admin accounts
connectToDB();
$query = "SELECT * FROM admins" or die(mysql_error());
$data = mysql_query($query) or die(mysql_error());
$numberOfAdmins = mysql_num_rows($data) or die(mysql_error());
//Check if the username corresponds to any found in the database
$usernameValid = false;
for($i = 0; $i < $numberOfAdmins; $i++)
{
if($usernameSubmitted == mysql_result($data, $i, "Username"))
{
$userToLogInAs = $i;
$usernameValid = true;
}
}
//If username is valid, check password
if($usernameValid != false)
{
//Passwords are held as blowfish encryptions for security. Encypt this so we can compare
$encryptedPasswordSubmitted = crypt($passwordSubmitted, '$2a$07$buzzybees5hivestottenhoe$');
if($encryptedPasswordSubmitted == mysql_result($data, $userToLogInAs, "Password"))
{
//Create a session variable so the user remains logged in
$_SESSION['username'] = $usernameSubmitted;
//User entered the correct username and password, redirect them to the website.
header('Location: Index.php');
}
}
//If we've got this far then the user didn't authenticate successfully.
$message = "<h2>Sorry, Invalid Credentials</h2><p>Check that you're tying your username and password correctly.</p>";
}
?>
下一页:
<?php
session_start();
if(!isset($_SESSION['username']))
{
//User not signed in, send them to the log in page
header('Location: Log-In.php');
}
?>
有什么想法吗?
谢谢丹尼
这只是一个猜测,但假设您只显示登录脚本的一部分代码:
在成功登录后,您不会在重定向后使用die()
,因此在此之后出现且您未在此处显示的任何代码都会被执行。如果您在那里操作$_SESSION
变量,则可能会导致您的问题。
为了安全起见,只需将您的代码更改为:
if($encryptedPasswordSubmitted == mysql_result($data, $userToLogInAs, "Password"))
{
//Create a session variable so the user remains logged in
$_SESSION['username'] = $usernameSubmitted;
//User entered the correct username and password, redirect them to the website.
header('Location: Index.php');
die(); // this is important!
}
看看这是否能解决问题。请注意,您需要在重定向的任何位置执行此操作。