我正在创建一个登录页面,其中输入了用户名和密码,然后根据数据库进行检查以查看它们是否匹配(我之前发布了此信息,但我的代码完全不正确,所以我不得不重新开始)单击提交按钮时,如果两个值匹配,则应将用户定向到主页(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();
}
?>
现在验证码。我已经用Google搜索了这个并找到了几百种方法,但这种方法最符合我的编码风格。它是不完整的,我想要一些帮助,如何正确完成它,然后将其放在上面的代码中。我的假设恰好在此评论之后:&#34; //检查用户名对密码&#34;。现在我已经看过两次这个版本,在一个版本中,检查是针对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很新,我真的很努力学习它。并且有太多的信息,其中大部分都不适合初学者。任何和所有的帮助将不胜感激。
答案 0 :(得分: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页面上,用户提交了他的用户名和密码,首先:检查我们是否真的收到了用户名和密码,以及三元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。
我希望我能说清楚。