【发布时间】:2014-03-31 00:11:21
【问题描述】:
当用户在我的网站上使用登录系统并且提交的凭据正确时,会设置会话和会话数据。但是会话数据不会从一个页面转移到另一个页面。在登录脚本中,我打印出会话数组,它显示所有内容都已设置。但是当我使用打印会话的相同代码转到另一个页面时,它显示会话中没有任何内容。 (是的,我在每个需要它的php页面的开头插入session_start())
登录.php
<?php
require("config.php");
if(!empty($_POST))
{
// This query retreives the user's information from the database using
// their username.
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
// The parameter values
$query_params = array(
':username' => $_POST['username']
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
// If they do, then we flip this to true
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['USER'] = $row;
/* print_r($_SESSION); */
session_write_close();
header("Location: index.php");
// Redirect the user to the index page.
die("Redirecting to the home page.");
}
else
{
print("Login Failed.");
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
header("Location: login.php");
exit;
}
}
echo $message;
?>
下一个脚本检查是否设置了会话。如果不是,它会将用户重定向到登录页面。
<?php
/*** begin the session ***/
session_start();
if(!isset($_SESSION['USER']))
{
// If they are not, we redirect them to the login page.
header("Location: ../login.php");
exit;
}
?>
【问题讨论】:
-
login.php似乎没有使用session_start(); -
config.php开始会话 -
这不是您问题的答案,但是,您永远不应该在会话 cookie 中存储用户信息。这是不安全的。生成一个随机序列,将会话 ID 设置为此随机序列,然后使用数据库中的会话表将此会话 ID 链接到用户数据。否则,在没有有效用户名/密码的情况下很容易登录到您的系统,或者很容易从存储在用户计算机上的 cookie 中获取密码。
-
@EliasSoares 用户信息不存储在 cookie 中。只有会话 ID 存储在那里 - 用户信息保存在服务器上。
-
您的会话可能无法正常工作的原因有很多。您可能在浏览器中禁用了 cookie,或者 php.ini 中的设置阻止了正确保存会话。好消息是网络上有大量关于 PHP 会话处理的文章。我建议阅读其中的一些(例如phpro.org/tutorials/Introduction-To-PHP-Sessions.html),进行一些您自己的实验(例如,转储 $_COOKIE 是一个很好的起点),然后,如果您仍然卡住,请再次提出问题有关您尝试过的事情的更多详细信息。