简体   繁体   English

使用 PDO 函数通过 MySQL 服务器验证用户名/密码

[英]Verifying username/password via MySQL server using PDO functions

I am having some problem connecting properly to the MySQL server using the PDO function.我在使用 PDO 功能正确连接到 MySQL 服务器时遇到了一些问题。 I can't query what I need from the database and I am not quite sure what PDO functions to use.我无法从数据库中查询我需要的内容,也不太确定要使用哪些 PDO 函数。 I GET 0 as a result of this.因此,我得到 0。 I wish to verify the password and username I enter via the database and make an if statement that launches the session if the information is correct.我希望验证我通过数据库输入的密码和用户名,并创建一个 if 语句,如果信息正确则启动会话。

Here is my UPDATED code:这是我的更新代码:

<?php
// if a value is given
if (isset($_POST['username' && 'password'));
{

    // starts the session created if login info is correct
    session_start();

    // connectivity to MySQL server
    $db = new PDO('mysql:host=host;dbname=name', 'username', 'password');

    // information entered in form made into a variable
    $username = PDO::quote($_POST['username']); 
    $password = PDO::quote($_POST['password']);

    // after pressing login, checking if the variables exist in the database
    if ($_POST['button'] == 'Login')
    {
        $query = $db->query("SELECT COUNT(*) FROM login WHERE username=:username AND password=:password");
        $query->bindValue(':username', $username, PDO::PARAM_STR);
        $query->bindValue(':password', $password, PDO::PARAM_STR);
        $query->execute();

        // Check the number of rows that match the SELECT statement 
        if($query = $db->fetch(PDO::FETCH_OBJ)) 
        {
            echo "No records found";
        }
        else
        {
            header("Location: members.php");
            $_SESSION['username'] = $_POST['username'];
        }
    }   
    // After pressing register, stores variable and adds it in register field
    else if ($_POST['register'] == 'Register')
    {
        header("Location: register.php");
        $_SESSION['usernamereg'] = $_POST['username'];
    }

    // If no button is pressed, send to index
    else
    {
        header("Location: http://www.gjertgjersund.com");
    }

// closes the if value is given statement
}
?>

<!DOCTYPE html>
<html>
<head>
    <title> Folder </title>
    <link rel="stylesheet" type="text/css" href="frontpage.css">
</head>
<body>

    <div id="box">
    <div id="wrap">


        <center>
        <img src="./img/logo.png" alt="logo">

        <form action='index.php' method='POST' autocomplete='off'>

        <div class="usernameform">
        <input type='text' name='username' style='border: none; font-size: 20px;'>
        </div>

        <br />

        <div class="passwordform">
        <input type='password' name='password' style='border: none; font-size: 20px;'>
        </div>

        <br />

        <div class="registerlogin">
        <input type='submit' name='button' value='Login' class='input'>
        <input type='submit' name='register' value='Register' class='inputtwo'>
        </div>

        </form>
        </center>

    </div>
    </div>

</body>
</html>

That's a very good question, partially because it demonstrates a lot of bad practices that, sadly, exist to this day, almost a decade since this question has been posted.这是一个非常好的问题,部分原因是它展示了许多糟糕的做法,遗憾的是,这些做法至今仍存在,距发布该问题已近十年。 Let's sort them out让我们整理一下

Connection联系

I am having some problem connecting properly to the MySQL server using the PDO function.我在使用 PDO 功能正确连接到 MySQL 服务器时遇到了一些问题。

That's a fair question and nowhere the connection is just a single line of code.这是一个公平的问题,没有任何地方连接只是一行代码。 Мany important options have to be set, see a canonical connection example I wrote. М任何重要的选项都必须设置,请参阅我写的规范连接示例 You can store the connection code in a separate file and then just include it in your scripts.您可以将连接代码存储在单独的文件中,然后将其包含在您的脚本中。

Password hashing密码散列

You should never store plain passwords in your database.你永远不应该在你的数据库中存储简单的密码。 Instead, password must be hashed , using a dedicated function made for the purpose - password_hash() .取而代之的是,必须对密码进行哈希处理,并使用专门为此目的创建的函数 - password_hash()

Then, to verify the password, you've go to use password_verify()然后,要验证密码,您必须使用password_verify()

Don't move any further until you have your passwords properly hashed.在您正确散列密码之前,不要再进一步。 Note that the field size for the hashed password must be 60 characters long.请注意,散列密码的字段大小必须为 60 个字符长。

The code to verify username and password验证用户名和密码的代码

Finally, now we can write the code.最后,现在我们可以编写代码了。 It could be much simpler, just a few lines.它可以简单得多,只需几行。 Actually, only one condition is needed.实际上,只需要一个条件。 We shouldn't provide any details as to whether login or username not found - just "Login and password don't match".我们不应该提供有关是否未找到登录名或用户名的任何详细信息 - 只是“登录名和密码不匹配”。 So here it goes:所以这里是这样的:

<?php
if (isset($_POST['username']))
{
    // get the PDO instance
    include 'pdo.php';

    // getting the record for the given username
    $stmt = $pdo->prepare("SELECT * FROM login WHERE username=?");
    $stmt->execute([$_POST['username']]);
    $user = $stmt->fetch();
    // verifying the password
    if ($user && password_verify($_POST['password'], $user['password']))
    {
        // starts the session created if login info is correct
        session_start();
        $_SESSION['username'] = $user['username'];
        header("Location: members.php");
        exit;
    } else {
        $error = "Login and password don't match";
    }
}

Here, we are checking whether such a user exists and whether the password matches in a single condition.在这里,我们正在检查是否存在这样的用户以及密码是否在单个条件下匹配。

You should not have to use ' in prepared statement and $username is string not integer您不必在准备好的语句中使用'并且$username是字符串而不是整数

$query = $db->query("SELECT * FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
$row_count = $query->rowCount();
 //{ remove it

Your if condition is wrong change您的if条件错误更改

// if a value is given
if (isset($_POST['username' && 'password'));
{

to

// if a value is given
if (isset($_POST['username']) and isset($_POST['password']))
{

Codepad键盘

Some databases may return the number of rows returned by a SELECT statement.某些数据库可能会返回 SELECT 语句返回的行数。 However, this behaviour is not guaranteed for all databases and should not be relied on see Manual .但是,并不能保证所有数据库都具有这种行为,因此不应依赖于手册 You can use COUNT(*) and fetchColumn() as in following query to emulate rowCount() .您可以在以下查询中使用COUNT(*)fetchColumn()来模拟rowCount()

$query = $db->query("SELECT COUNT(*) FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
    // Check the number of rows that match the SELECT statement 
    if($query->fetchColumn() == 0) {
        echo "No records found";
     }else{
            //CODE FOR Success 
            //Etc
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM