PHP用户名和密码验证检查

PHP用户名和密码验证检查,php,validation,login,Php,Validation,Login,我正在创建一个登录页面,其中输入用户名和密码,然后对照数据库检查它们是否匹配(我之前已经发布了此页面,但我的代码完全不正确,因此我必须重新开始)。单击提交按钮后,用户应被定向到主页(index.php)如果两个值匹配,或者出现一条错误消息,说明“登录无效。请重试。”非常简单的基本信息。然而,我无法得到任何变化的工作 这是我没有验证检查的代码。我相信这个代码是正确的,但如果不是,请有人解释一下原因。我不是要求任何人写任何代码,只是解释为什么它不能正常工作 <?php function Pa

我正在创建一个登录页面,其中输入用户名和密码,然后对照数据库检查它们是否匹配(我之前已经发布了此页面,但我的代码完全不正确,因此我必须重新开始)。单击提交按钮后,用户应被定向到主页(index.php)如果两个值匹配,或者出现一条错误消息,说明“登录无效。请重试。”非常简单的基本信息。然而,我无法得到任何变化的工作

这是我没有验证检查的代码。我相信这个代码是正确的,但如果不是,请有人解释一下原因。我不是要求任何人写任何代码,只是解释为什么它不能正常工作

<?php

function Password($UserName)
{   

//database login
$dsn = 'mysql:host=XXX;dbname=XXX';
$username='*****';
$password='*****';
//variable for errors
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
//try to run code
try {
//object to open database
$db = new PDO($dsn,$username,$password, $options);
//check username against password
    $SQL = $db->prepare("Select USER_PASSWORD FROM user WHERE USER_NAME = :USER_NAME");
    $SQL->bindValue(':USER_NAME', $UserName);
    $SQL->execute();
    $username = $SQL->fetch();

    if($username === false)
        {
            $Password = null;
        }
    else
        {
            $Password = $username['USER_PASSWORD'];
        }

    return $Password;
    $SQL->closeCursor();
    $db = null;

    } catch(PDOException $e){
        $error_message = $e->getMessage();
        echo("<p>Database Error: $error_message</p>");
        exit();
    }
?>

我知道我在这里要求很多。但我对PHP非常陌生,我正在努力学习它。而且有太多的信息在那里,而且大部分不是给初学者的。我们将非常感谢您的任何帮助

首先,让我们假设我们有一个PDO连接,就像您已经做的那样,例如使用以下函数:

您可以执行以下操作:

// Usage:   $db = connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre:     $dbHost is the database hostname, 
//          $dbName is the name of the database itself,
//          $dbUsername is the username to access the database,
//          $dbPassword is the password for the user of the database.
// Post:    $db is an PDO connection to the database, based on the input parameters.
function connectToDataBase($dbHost, $dbName, $dbUsername, $dbPassword)
{
    try
    {
         return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
    }
    catch(Exception $PDOexception)
    {
        exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
    }
}
到目前为止,我们有和你一样的东西

现在,我假设我们在一个PHP页面上,用户提交了用户名和密码,首先:检查我们是否真的收到了用户名和密码,使用三元运算符:

// receive parameters to log in with.
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
现在,您可以验证这些输入是否已实际发布:

// Check if all required parameters are set and make sure
// that a user is not logged in already

if(isset($_SESSION['loggedIn']))
{
    // You don't want an already logged in user to try to log in.
    $alrLogged = "You're already logged in.";
    $_SESSION['warningMessage'] = $alrLogged;
    header("Location: ../index.php");
}
else if($userName && $password)
{
    // Verify an user by the email address and password
    // submitted to this page
    verifyUser($userName, $password, $db);
}
else if($userName && (!($password)))
{
    $noPass = "You didn't fill out your password.";
    $_SESSION['warningMessage'] = $noPass;
    header("Location: ../index.php");
}
else if((!$userName) && $password)
{
    $noUserName = "You didn't fill out your user name.";
    $_SESSION['warningMessage'] = $noUserName;
    header("Location: ../index.php");
}
else if((!$userName) && (!($password)))
{
    $neither = "You didn't fill out your user name nor did you fill out your password.";
    $_SESSION['warningMessage'] = $neither;
    header("Location: ../index.php");
}
else
{
    $unknownError = "An unknown error occurred.". NL. "Try again or <a href='../sites/contact.php' title='Contact us' target='_blank'>contact us</a>.";
    $_SESSION['warningMessage'] = $unknownError;
    header("Location: ../index.php");
}
如第一个else if语句中所述:

// Usage:   verifyUser($userName, $password, $db);
// Pre:     $db has already been defined and is a reference
//          to a PDO connection.
//          $userName is of type string.
//          $password is of type string.
// Post:    $user exists and has been granted a session that declares
//          the fact that he is logged in.
function verifyUser($userName, $password, $db)
{
    $userExists = userExists($userName, $db); // Check if user exists with that username.
    if(!($user))
    {
        // User not found.
        // Create warning message.
        $notFound= "User not found.";
        $_SESSION['warningMessage'] = $notFound;
        header("Location: ../index.php");
    }
    else
    {
        // The user exists, here you can use your smart function which receives
        // the hash of the password of the user:
        $passwordHash = Password($UserName);
        // If you have PHPass, an awesome hashing library for PHP
        // http://www.openwall.com/phpass/
        // Then you can do this:
        $passwordMatch = PHPhassMatch($passwordHash , $password);
        // Or you can just create a basic functions which does the same;
        // Receive 1 parameter which is a hashed password, one which is not hashed,
        // so you hash the second one and check if the hashes match.

        if($passwordMatch)
        {
            // The user exists and he entered the correct password.
            $_SESSION['isLoggedIn'] = true;
            header("Location: ../index.php");
            // Whatever more you want to do.
        }
        else
        {
            // Password incorrect.
            // Create warning message.
            $wrongPass = "Username or password incorrect."; // Don't give to much info.
            $_SESSION['warningMessage'] = $wrongPass;
            header("Location: ../index.php");
        }
    }
}
userExists($userName,$db)函数可以是:

function userExists($userName, $db)
{
    $stmt = $db->prepare("SELECT * FROM users WHERE USER_NAME = :USER_NAME;");
    $stmt->execute(array(":USER_NAME "=>$userName));
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if($result)
    {
        // User exists.
        return true;
    }
    // User doesn't exist.
    return false;
}
其中,函数密码类似于:

function Password($UserName)
{
    $stmt = $db->prepare("Select USER_PASSWORD FROM user WHERE USER_NAME = :USER_NAME;");
    $stmt->execute(array(":USER_NAME"=>UserName));
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if($result)
    {
        return $result['USER_PASSWORD'];
    }
    // No result.
    return false;
}
同样,请确保您没有匹配纯文本密码,或基本shai1、md5加密等。我真的建议您查看PHPass


我希望我能说清楚。

您的函数(主要是
Login()
)在一个类中吗?如果不是,你不应该引用
$this
我知道你说它不工作,但发生了什么?你得到了什么?如果(!$this->($username,$password)),你在
中缺少了一些东西。你想调用哪个方法?这行代码在做什么<代码>如果(!$this->($username,$password))
代码看起来不完整。如果(!$this->($username,$password)){return false;}应该包含一个操作什么是$stmt?我从来没见过。另外,我完全理解您将把代码放在哪里来代替我所写的内容,但是您将把密码匹配验证放在哪里?$stmt是$statement的缩写。该代码将在Password($UserName)函数中。您将在收到密码后立即进行验证。让我编辑我的答案。我会在谷歌上搜索这个语句,让自己更加熟悉它。谢谢您的帮助。$语句不是内置函数,您可以随意调用它。看看我的更新。所以,让我弄清楚这一点,这样我就不会感到困惑。你会把你的第一行$stmt放在我评论“//检查用户名和密码”的正下方,对吗?那么我可以检查“用户名”而不是“约翰”吗?如果是这样的话,这个代码和另一个代码在哪里?还是你失去了我?
// Usage:   verifyUser($userName, $password, $db);
// Pre:     $db has already been defined and is a reference
//          to a PDO connection.
//          $userName is of type string.
//          $password is of type string.
// Post:    $user exists and has been granted a session that declares
//          the fact that he is logged in.
function verifyUser($userName, $password, $db)
{
    $userExists = userExists($userName, $db); // Check if user exists with that username.
    if(!($user))
    {
        // User not found.
        // Create warning message.
        $notFound= "User not found.";
        $_SESSION['warningMessage'] = $notFound;
        header("Location: ../index.php");
    }
    else
    {
        // The user exists, here you can use your smart function which receives
        // the hash of the password of the user:
        $passwordHash = Password($UserName);
        // If you have PHPass, an awesome hashing library for PHP
        // http://www.openwall.com/phpass/
        // Then you can do this:
        $passwordMatch = PHPhassMatch($passwordHash , $password);
        // Or you can just create a basic functions which does the same;
        // Receive 1 parameter which is a hashed password, one which is not hashed,
        // so you hash the second one and check if the hashes match.

        if($passwordMatch)
        {
            // The user exists and he entered the correct password.
            $_SESSION['isLoggedIn'] = true;
            header("Location: ../index.php");
            // Whatever more you want to do.
        }
        else
        {
            // Password incorrect.
            // Create warning message.
            $wrongPass = "Username or password incorrect."; // Don't give to much info.
            $_SESSION['warningMessage'] = $wrongPass;
            header("Location: ../index.php");
        }
    }
}
function userExists($userName, $db)
{
    $stmt = $db->prepare("SELECT * FROM users WHERE USER_NAME = :USER_NAME;");
    $stmt->execute(array(":USER_NAME "=>$userName));
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if($result)
    {
        // User exists.
        return true;
    }
    // User doesn't exist.
    return false;
}
function Password($UserName)
{
    $stmt = $db->prepare("Select USER_PASSWORD FROM user WHERE USER_NAME = :USER_NAME;");
    $stmt->execute(array(":USER_NAME"=>UserName));
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    if($result)
    {
        return $result['USER_PASSWORD'];
    }
    // No result.
    return false;
}