查询SQL获取用户名并返回密码

发布于 2024-11-29 15:41:58 字数 478 浏览 0 评论 0原文

我有一个用户名和密码的数据库。我需要创建一个“忘记密码”功能,并让它在表中搜索用户名并返回该用户的密码。然后我希望它发送一封电子邮件,说明姓名和密码。

这是我用于查询特定用户的数据库的工作代码:

<?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'; 
}
}
?>

I have a database of usernames and passwords. I need to create a "Forgot password" function and have it search the table for a username and return that user's password. Then I would like it to send an email saying the name and password.

Here is my working code for querying the database for a specific user:

<?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'; 
}
}
?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

蓝眸 2024-12-06 15:41:59

首先要做的事情是:您可能想确保您不会通过登录获得 SQL 注入,因为您实际上是将用户输入注入到您的查询中......这是一个大禁忌。

交换这个:

$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)';

    }
?>

编辑:添加密码恢复功能

对于您在下面请求的密码恢复功能,您可以尝试如下操作:

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 ;

祝你好运!

First thing's first: you might want to make sure that you won't get SQL-injected via your login, as you're literally injecting the user input into your query... big no-no.

Swap this:

$query = "SELECT * FROM myDatabase WHERE name = '" .$_POST['nameQuery']. "'";  

...for this:

$query = sprintf(
    'SELECT * FROM myDatabase WHERE name = \'%s\'', 
    mysql_real_escape_string($_POST['nameQuery'])
);

Next up is what you asked for: a way to get both the users username and password. While I don't recommend that you actually store the password in plaintext for everyone to view, it's a decision you have to make on your own.

This snippet will do the deed:

<?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

For the password recovery-functionality you requested below, you can try something like this:

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>

Note that I haven't had time to actually test the code, but I think it'll work just fine with some minor adjustments. Oh, before I forget, you'll need to add the following table to the DB:

Table structure for table 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 ;

Good luck!

冷清清 2024-12-06 15:41:59

虽然与您原来的问题无关,但我想指出,以纯文本形式存储密码是一个坏主意。您应该将密码的哈希版本存储在数据库中。然后,您可以对用户输入进行哈希处理,并将其与登录数据库中的内容进行比较。

相反,您忘记的密码应该创建一个新的(临时)密码,并将该哈希值存储在数据库中,同时将纯文本密码发送到存档的电子邮件帐户。

While tangential to your original question, I would like to point out that storing passwords in plain text is a bad idea. You should store hashed versions of the password in the database. You can then hash user input and compare it to what is in the database for logging in.

Instead, your forgot password should create a new(temporary) password, and store the hash of that in the database, while sending the plain text password to the email account on file.

表情可笑 2024-12-06 15:41:59

只需阅读结果:

/* ... */
if (mysql_num_rows($result) > 0) {
  // User exists
  $row = mysql_fetch_row($result);
  print_r($row);
}
/* ... */

更一般地说:您的代码中存在 SQL 注入漏洞,请查看该主题,否则攻击者将能够读取您所有用户的密码。

另外,不建议将密码以明文形式存储在数据库中。请使用 sha1 或 sha256 等哈希算法来存储密码。

Just read the result:

/* ... */
if (mysql_num_rows($result) > 0) {
  // User exists
  $row = mysql_fetch_row($result);
  print_r($row);
}
/* ... */

On a more general note: You have a SQL injection vulnerability in your code, please look into that topic, or attackers will be able to read all your user's passwords.

Also, it is not advised to store the password in clear text in you database. Please use a hashing algorithm like sha1 oder sha256 to store passwords.

韶华倾负 2024-12-06 15:41:59

我建议您将表设计更改为

  • UserName
  • Password ' store hash
  • 密码检索问题 ' store hash
  • 密码检索答案 ' store hash

登录时根据哈希密码检查用户,类似这样

$_POST['password']=sha1($_POST['password']);

登录时然后使用 sql
从 tbl 中选择 col1,col2,..,其中 user=?和密码=?然后用 $_POST['username'], $_POST['password'] 填充参数,

因此使用 Prepared Statement 或 PDO

当用户忘记密码时使用相同的逻辑

I will recommend you to change your table design to

  • UserName
  • Password ' store hash
  • Password Retrieval Question ' store hash
  • Password Retrieval Answer ' store hash

When login check the user against the hashed password, something like this

$_POST['password']=sha1($_POST['password']);

When loggin in then use sql like
select col1,col2,.. from tbl where user=? and password=? and then fill the parameter with $_POST['username'], $_POST['password']

so use Prepared Statement or PDO

use the same logic when user forgot his password

亽野灬性zι浪 2024-12-06 15:41:59
<?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'; 
    }
}
?>
<?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'; 
    }
}
?>
廻憶裏菂餘溫 2024-12-06 15:41:59

您必须从 mysql_query 结果(存储在 $result 变量中)检索用户名和密码,如下所示:

$row = mysql_fetch_array($result);
$username = $row['username'];
$password = $row['password'];

然后使用 php 的 mail() 函数发送电子邮件。

You have to retrieve the username and password from the mysql_query result (stored in the $result variable) as such:

$row = mysql_fetch_array($result);
$username = $row['username'];
$password = $row['password'];

Then use php's mail() function to send the e-mail.

只是我以为 2024-12-06 15:41:58

请勿将密码存储在数据库中。绝不能存储明文密码。您应该存储密码的哈希值,以帮助防止它们在其他网站上使用。有关详细信息,请参阅在数据库中存储密码的最佳方式

DO NOT store passwords in your database. Cleartext passwords should never be stored. You should be storing a hash of the passwords to help prevent them being used on other sites. See Best way to store password in database for more information.

雄赳赳气昂昂 2024-12-06 15:41:58

您的代码不安全!您的 $_POST['nameQuery'] 是通往 SQL 注入

最低的安全性是转义并清理所有输入

$nameQuery = mysql_real_escape_string ($_POST['nameQuery']);

黄金法则:永远不要相信传入的数据

Your code is NOT secured ! Your $_POST['nameQuery'] is a gorgeous opened door to SQL Injection

The minimum security is to escape and sanitize all your inputs

$nameQuery = mysql_real_escape_string ($_POST['nameQuery']);

The golden rule: never trust incoming data.

平安喜乐 2024-12-06 15:41:58

社区维基

不要。因为这意味着您将保存可检索的密码。最好向他们的电子邮件发送一个密码更改链接,以便访问一次性密码重置页面。这样,在有权访问该用户电子邮件的人完成重置周期之前,密码不会更改。

通过这种方式,您可以适当地散列密码并仅根据散列检查传入的密码。

此外,我建议查看 php 的 PDO,因为您当前正在创建容易受到 sql 注入影响的 sql 查询。

Community Wiki:

Don't. Because that means you'll be saving retrievable passwords. Better to send a password-changing link to their email that gives access to a one-time password reset page. In this way, the password isn't changed until a reset cycle is completed by someone with access to that user's email.

In that way you can appropriately hash passwords and check incoming passwords against a hash only.

In addition, I recommend looking into php's PDO, because you're currently creating sql queries that are succeptible to sql-injection.

箜明 2024-12-06 15:41:58

我有一些建议给你

  1. 不要向人们发送密码,而是向他们提供一个更改密码的链接
  2. 查看 kjetilh 的建议

祝你好运,编码愉快

I have a few suggestions for you

  1. Don't send people there password but rather provide them with a link to change there password
  2. Look into kjetilh's suggestion

good luck and happy coding

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文