我已经学习 PHP 和 MySQL 一段时间了,我遇到了一个问题。我已经创建了一个用户数据库(MySQL)、登录表单和页面,您应该在成功登录后重定向到这些页面。
登录页面
<?php
require_once 'login.php'; //connecting to db
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
session_start(); //
if (isset($_POST['username']) &&
isset($_POST['password']))
{
$username = $_POST["username"];
$password = $_POST["password"];
$salt1 = "qm&h*";
$salt2 = "pg!@";
$query = "SELECT * FROM login WHERE username='$username'";
$result = mysql_query($query);
if (mysql_num_rows($result) == 0) die("Wrong username or password.");
elseif (mysql_num_rows($result))
{
$row = mysql_fetch_row($result);
$crypt_login_pass = md5("$salt1$password$salt2");
if ($crypt_login_pass == $row[2])
{
$_SESSION['username'] = $username;
$_SESSION['password'] = $crypt_pass;
header("Location: index_account.php");
exit;
}
else {
die("Wrong username or password.");
}
}
}
?>
代码运行完美,直到我添加了header("Location: index_account.php")
. 我曾经有过die("You are now logged in.")
。这是您应该被重定向到的页面:
<?php
session_start();
if (isset($_SESSION['username']) &&
isset($_SESSION['password']))
{
$username = $_SESSION['username'];
$password = $_SESSION['password'];
echo "Your username is '$username'
and your crypted password is '$password'.";
}
else echo "Please <a href=index.php>click here</a> to log in.";
?>
所有这些代码都在本地主机上运行。问题是 $_SESSION['username'] 和 $_SESSION['password'] 不会转移到第二页(index_account.php)。我读过很多帖子,我发现最相似的是:Session variables lost after header redirect but without answear。请注意,这是我的第一种编程语言(不包括 HTML 和 CSS),对此我还是很陌生。
PS对不起我的英语。这不是我的母语。
提前致谢!