1

我正在创建一个登录页面,在其中输入用户名和密码,然后检查数据库以查看它们是否匹配(我之前已经发布过,但我的代码完全不正确,所以我不得不重新开始)点击提交按钮,如果两个值匹配,用户应该被引导到主页 (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();
    }
?>

现在是验证码。我用谷歌搜索了这个并找到了数百种方法,但这种方法最符合我的编码风格。它是不完整的,我想要一些关于如何正确完成它以及将它放在上面代码中的位置的帮助。我的假设是在此评论之后:“//检查用户名与密码”。现在我已经看过这个版本两次了,在一个版本中检查的是 txtUserName 而另一个只是用户名。我相信在每个 if 语句之后应该有 else 语句,以将它们引导到 index.php 页面。此外,第三个 if 语句是检查密码是否与用户名匹配。我不明白这一点的变化。它们太复杂了。

function Login()
{     
if(empty($_POST['txtUserName']))     
{         
    $this->HandleError("UserName is empty!");         
    return false;     
}          
if(empty($_POST['txtPassword']))     
{         
    $this->HandleError("Password is empty!");
            return false;     
}           

$username = trim($_POST['txtUserName']);
    $password = trim($_POST['txtPassword']);           

if(!$this->($username,$password))     
{         
    return false;     
}           
} 

我知道我在这里问了很多。但我对 PHP 很陌生,并且非常努力地学习它。而且那里的信息太多了,其中大部分不适合初学者。任何和所有的帮助将不胜感激。

4

1 回答 1

3

首先,假设我们有一个 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>");
    }
}

这样您就可以拥有这样的数据库连接:

$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';

$db = connectToDataBase($host, $databaseName, $user, $pass);

到目前为止,我们拥有与您相同的东西。

现在,我假设我们在用户提交用户名和密码的 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");
}

现在,让我们假设一切顺利,并且您已经在变量 $db 中存储了一个数据库连接,那么您可以使用该函数

verifyUser($userName, $password, $db);

就像第一个 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。

我希望我清楚自己。

于 2013-03-06T22:19:43.407 回答