1

ユーザー名とパスワードを入力し、データベースと照合して一致するかどうかを確認するログイン ページを作成しています (以前に投稿しましたが、コードが完全に間違っていたため、最初からやり直す必要がありました)。ボタンをクリックすると、2 つの値が一致するか、「無効なログインです。もう一度お試しください」というエラー メッセージが表示された場合、ユーザーはホームページ (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();
    }
?>

次に検証コードです。これをグーグルで検索したところ、数百の方法が見つかりましたが、この方法が私のコーディング スタイルに最もよく一致しています。それは不完全であり、適切に終了する方法と、上記のコード内のどこに配置するかについて、いくつかの助けが必要です. 私の仮定は、このコメントの直後です:「//パスワードに対してユーザー名を確認してください」。今、私はこのバージョンを 2 回見ましたが、1 つのバージョンでは txtUserName のチェックが行われ、もう 1 つのバージョンではユーザー名だけがチェックされます。それぞれの if ステートメントの後に、それらを index.php ページに誘導するための else ステートメントが必要だと思います。また、3 番目の 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 に答える