Перво-наперво: возможно, вы захотите убедиться, что вы не получите 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>
Обратите внимание, что у меня естьУ меня не было времени, чтобы на самом деле протестировать код, но я думаю, что он будет хорошо работать с некоторыми небольшими изменениями.О, прежде чем я забуду, вам нужно добавить следующую таблицу в БД:
Структура таблицы для таблицы 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 ;
Удачи!