我正在设计一个登录系统作为个人项目,我正在尝试将用户的电子邮件和密码哈希(我应该存储明文密码?)存储在cookie中,以便网站知道用户的帐户登录。
麻烦的是,一旦我把我的setcookie();在if语句中的命令,它们停止工作。我知道if语句正在被访问,因为正在从其中调用其他代码,但就好像忽略了setcookie()。
以下是代码:
<?php
$email = $_POST[email];
$password = $_POST[password];
$passwordHash = sha1($password);
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "password";
$dbname = "db";
mysql_connect($dbhost,$dbuser,$dbpass)
or die("Error: Failed to connect to database");
mysql_select_db($dbname)
or die("Error: Failed to select databse");
$query = "SELECT * FROM users WHERE user = '$email'";
$sql = mysql_query($query);
while($r = mysql_fetch_array($sql)) {
if($passwordHash == $r[passwordhash]) {
setcookie("Email", $email, time()+3600);
setcookie("PasswordHash", $passwordHash, time()+3600);
echo "added cookie";
}
else {
echo "Incorrect password";
}
}
?>
答案 0 :(得分:1)
我应该存储纯文本密码吗?
不,永远,不。这将是一个重大的安全漏洞,想象我使用你的电脑一分钟,如果你登录并检查你的cookie,我会立即得到你的密码
答案 1 :(得分:1)
由setcookie定义的cookie与其他标头一起发送(必须在任何输出包括空格之前发送)。我认为这个问题就在这里
的更新强>
我会尝试header('Location: somepage.html')
代替setcookie
,以确定它是否是罪魁祸首。
答案 2 :(得分:0)
为什么不使用PHP的会话功能只是向用户发送会话ID而不是他们的登录凭据?此外,您的代码存在多个问题:
$_POST[email]
将发出警告。你可能意味着$_POST['email']
。我建议改变代码:
<?php
$email = isset($_POST['email']) ? $_POST['email'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$passwordHash = sha1($password);
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "password";
$dbname = "db";
mysql_connect($dbhost,$dbuser,$dbpass) or die("Error: Failed to connect to database");
mysql_select_db($dbname) or die("Error: Failed to select databse");
$query = "SELECT * FROM users WHERE user = '".mysql_real_escape_string($email)."' LIMIT 1";
$sql = mysql_query($query);
if (mysql_num_rows($sql) == 1) {
$r = mysql_fetch_array($sql);
if ($passwordHash == $r['passwordhash']) {
session_start();
$_SESSION['user_id'] = $email;
}
else {
echo "Incorrect password";
}
}
?>