我有一个用户名和密码的数据库。我需要创建一个"忘记密码"功能,并有它搜索表的用户名和返回该用户的密码。然后我想让它发送一封电子邮件,告诉我名字和密码。
下面是我为特定用户查询数据库的工作代码:
<?php
session_start();
include "config.php";
if($_POST['nameQuery']) {
$query = "SELECT * FROM myDatabase WHERE name = '" .$_POST['nameQuery']. "'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
//User exists
echo '1';
} else {
mysql_query($query);
//User does not exist
echo '0';
}
}
?>
不要在数据库中存储密码。永远不要存储明文密码。您应该存储密码的散列,以防止它们被其他网站使用。有关详细信息,请参阅在数据库中存储密码的最佳方法。
您的代码不安全 !你的$_POST['nameQuery']
是一个华丽的打开大门SQL注入
最低限度的安全性是逃避和消毒所有输入
$nameQuery = mysql_real_escape_string ($_POST['nameQuery']);
黄金法则:永远不要相信传入的数据。
社区维基:
没有。因为这意味着你将保存可检索的密码。最好给他们的电子邮件发送一个密码更改链接,让他们可以访问一次性密码重置页面。通过这种方式,密码不会被更改,直到重置周期被访问该用户的电子邮件的人完成。
通过这种方式,您可以适当地对密码进行散列,并仅根据散列检查传入密码。
此外,我建议查看php的PDO,因为您当前创建的sql查询容易受到sql注入的影响。
我有一些建议给你
- 不要给人们发送密码,而是提供一个更改密码的链接
- 调查kjetilh的建议
祝你编码顺利
首先:您可能想要确保您不会通过登录获得SQL-injected
,因为您实际上是将用户输入注入您的查询…大禁忌。
互换:
$query = "SELECT * FROM myDatabase WHERE name = '" .$_POST['nameQuery']. "'";
…:
$query = sprintf(
'SELECT * FROM myDatabase WHERE name = ''%s''',
mysql_real_escape_string($_POST['nameQuery'])
);
接下来是你所要求的:一种获取用户名和密码的方法。虽然我不建议您将密码以明文形式存储以供所有人查看,但这是您必须自己做出的决定。
下面的代码段将完成这个任务:
<?php
//Get the data from the DB
$query = sprintf(
'SELECT * FROM myDatabase WHERE name = ''%s''',
mysql_real_escape_string($_POST['nameQuery'])
);
$result = mysql_query($query);
$user_info = mysql_fetch_assoc($result);
//Check if it's valid
if( isset($user_info['name']) ) {
//Construct the message
$message = 'Your username is: ' . $user_info['name'] . "'n"
$message .= 'Your password is: ' . $user_info['password'] . "'n";
//Send it to the appropriate email
$status = mail(
$user_info['email'],
'Password recovery for ' . $user_info['name'],
$message
);
//Check if it actually worked
if( $status ) echo 'Mail sent. Check your inbox. Login again. Thank you.';
else echo 'The password recovery couldn''nt be sent. Please try again later.';
} else {
echo 'No user found with the supplied username.',
'Please try again (with another username)';
}
?>
Edit: Adding password recovery-functionality
对于您在下面请求的密码恢复功能,您可以尝试这样做:
recover_password.php:
<?php
session_start();
//mysql_connect()-here
//Initalize the variable
$do_update_password = false;
//Grab the token
$token = isset($_REQUEST['token'])? $_REQUEST['token'] : '';
$is_post_request = isset($_POST['update_pwd'])? true : false;
$is_recovery_request = isset($_POST['request_recovery'])? true : false;
$message = '';
//Check if we're supposed to act upon a token
if( $is_recovery_request ) {
//Grab the email
$email = isset($_POST['email'])? $_POST['email'] : '';
//Create the query, execute it and fetch the results
$sql = sprintf(
'SELECT `user_id` FROM myDatabase WHERE `email` = ''%s''',
mysql_real_escape_string($email)
);
$result = mysql_query($sql);
$user_info = mysql_fetch_assoc($result);
//Validate the response
if( isset($user_info['user_id') ) {
//Let's generate a token
$date = date('Y-m-d H:i:s');
$token = md5($email . $date);
//Create the "request"
$sql = sprintf(
'INSERT INTO myRequests (`user_id`, `token`, `date`) VALUES (''%s'', ''%s'', ''%s'')',
$user_info['user_id'],
mysql_real_escape_string($token),
$date
);
$result = mysql_query($sql);
//Validate
if( mysql_affected_rows($result) == 1 ) {
//Construct the message
$message = 'Your username is: ' . $user_info['email'] . "'n"
$message .= 'Please click on the following link to update your password: http://yoursite.com/request_password.php?token=' . $token . "'n";
//Send it to the appropriate email
$status = mail(
$email,
'Password recovery for ' . $email,
$message
);
//Check if it actually worked
if( $status ) {
echo 'Mail sent. Check your inbox. Login again. Thank you.';
} else {
echo 'The password recovery couldn''nt be sent. Please try again later.';
}
} else {
$message = 'The DB-query failed. Sorry!';
}
} else {
$message = 'The specified e-mail address could not be found in the system.';
}
} elseif( $token != '' ) {
//Check so that the token is valid length-wise (32 characters ala md5)
if( !isset($token[31]) || !isset($token[32]) ) {
$message = 'Invalid token!';
} else {
//Construct the query and execute it
$sql = sprintf(
'SELECT `user_id` FROM myRequest WHERE `token` = ''%s''',
mysql_real_escape_string($token);
);
$result = mysql_query($sql);
//Fetch the rows
$request_info = mysql_fetch_assoc($result);
//Check for a valid result
if( isset($request_info['user_id']) ) {
$message = 'Update your password below.';
$do_update_password = true;
} else {
$message = 'No record found for the following token: ' . $token);
}
}
} elseif( $is_post_request ) {
//Grab the new password
$password = isset($_POST['password'])? $_POST['password'] : '';
//Construct the query
$sql = sprintf(
'UPDATE myDatabase SET `password` = ''%s'' WHERE `user_id` = ( SELECT `user_id` FROM myRequest WHERE `token` = ''%s'' )',
mysql_real_escape_string($password),
mysql_real_escape_string($token)
);
//Execute it, and check the results
$result = mysql_query($sql);
if( $result !== false ) {
//Did we succeed?
if( mysql_affected_rows($result) === 1 ) {
//Remove the old recovery-request
$sql = sprintf(
'DELETE FROM myRequests WHERE `token` = ''%s''',
mysql_real_escape_string($token)
);
$result = mysql_query($sql);
//^We don't actually need to validate it, but you can if you want to
$message = 'Password updated. Go have fun!';
} else {
$message = 'Could not update the password. Are you sure that the token is correct?';
}
} else {
$message = 'Error in the SQL-query. Please try again.';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Password recovery</title>
<style>
form > * { display: block; }
</style>
</head>
<body>
<h1><?php echo $message; ?></h1>
<?php if( $do_update_password ): ?>
<form method="post">
<label for="token">Token:</label>
<input type="text" name="token" id="token" value="<?php echo $token; ?>" />
<label for="password1">Password:</label>
<input type="text" name="password[]" id="password1" />
<label for="password2">Password (again):</label>
<input type="text" name="password[]" id="password2" />
<input type="submit" name="update_pwd" value="Update your password!" />
</form>
<?php elseif($is_post_request && $token != ''): ?>
<h2>Request that might've updated your password. Exciting!</h2>
<?php else: ?>
<form method="post">
<label for="email">E-mail address:</label>
<input type="text" name="email" id="email" />
<input type="submit" name="request_recovery" value="Request a new password" />
</form>
<?php endif; ?>
</body>
</html>
请注意,我没有时间实际测试代码,但我认为只要做一些小的调整,它就会工作得很好。哦,在我忘记之前,您需要将以下表添加到DB:
表myRequests
CREATE TABLE IF NOT EXISTS `myRequests` (
`request_id` int(6) NOT NULL AUTO_INCREMENT,
`token` varchar(32) NOT NULL,
`user_id` int(6) NOT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (`request_id`),
UNIQUE KEY `token` (`token`,`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
祝你好运!
虽然与您最初的问题无关,但我想指出,以纯文本形式存储密码是一个坏主意。您应该在数据库中存储密码的散列版本。然后,您可以对用户输入进行散列,并将其与登录数据库中的内容进行比较。
相反,您忘记的密码应该创建一个新的(临时)密码,并将其散列存储在数据库中,同时将纯文本密码发送到文件中的电子邮件帐户。
直接读取结果:
/* ... */
if (mysql_num_rows($result) > 0) {
// User exists
$row = mysql_fetch_row($result);
print_r($row);
}
/* ... */
更一般的提示:你的代码中有SQL注入漏洞,请查看该主题,否则攻击者将能够读取所有用户的密码。
另外,不建议将密码以明文形式存储在数据库中。请使用sha1 oder sha256等散列算法存储密码
我建议您将您的表设计更改为
- 用户名
- 密码存储散列
- 密码检索问题存储散列
- 密码检索答案存储散列
登录时根据散列密码检查用户,如下所示
$_POST['password']=sha1($_POST['password']);
登录时使用sql,如
选择col1、col2 . .From TBL where user=?和密码= ?然后用$_POST['username'], $_POST['password']填充参数
所以使用预处理语句或PDO
在用户忘记密码时使用相同的逻辑
<?php
session_start();
include "config.php";
if($_POST['nameQuery']) {
$query = "SELECT * FROM myDatabase WHERE name = '" .mysql_real_escape_string($_POST['nameQuery']). "'";
$result = mysql_query($query) or die ('Error: '.mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_assoc($result);
$message = 'Your password is: '.$row['password'];
if(mail($row['user_email'], 'Lost password', $message)){
echo 'Password sent';
}
} else {
echo 'Nu such user';
}
}
?>
您必须从mysql_query结果(存储在$result
变量中)检索用户名和密码,如下所示:
$row = mysql_fetch_array($result);
$username = $row['username'];
$password = $row['password'];
然后使用php的mail()函数发送电子邮件。