簡體   English   中英

PHP用戶名和密碼驗證檢查

[英]PHP UserName and Password Validation Check

我正在創建一個登錄頁面,其中輸入了用戶名和密碼,然后根據數據庫檢查它們是否匹配(我之前發布了這個但我的代碼完全不正確所以我必須重新開始)點擊提交按鈕用戶應該被定向到主頁(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很新,我真的很努力學習它。 並且有太多的信息,其中大部分都不適合初學者。 任何和所有的幫助將不勝感激。

首先,讓我們假設我們有一個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頁面上,首先:檢查我們是否真的收到了用戶名和密碼,以及三元oprator:

// 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);

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

我希望我能說清楚自己。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM