当我注册为新用户,然后尝试以该用户身份登录时,无法识别用户名和/或密码。我已经在另一个应用程序中成功使用了此登录系统,但是当我将其插入新应用程序时,它开始出现此问题。我已经检查了所有内容,但似乎无法找到问题所在。非常感谢任何想法。
以下是代码:
<?php
function find_admin_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE username = '{$safe_username}' ";
$query .= "LIMIT 1";
$admin_set = mysqli_query($connection, $query);
confirm_query($admin_set);
if($admin = mysqli_fetch_assoc($admin_set)) {
return $admin;
} else {
return null;
}
}
function password_encrypt($password) {
$hash_format = "$2y$10$"; // Tells PHP to use Blowfish with a "cost" of 10
$salt_length = 22;
$salt = generate_salt($salt_length);
$format_and_salt = $hash_format . $salt;
$hash = crypt($password, $format_and_salt);
return $hash;
}
function generate_salt($length) {
// Not 100% unique, not 100% random, but good enough for a salt
// MD5 returns 32 characters
$unique_random_string = md5(uniqid(mt_rand(), true));
// Valid characters for a salt are [a-zA-Z0-9./]
$base64_string = base64_encode($unique_random_string);
// But not '+' which is valid in base64 encoding
$modified_base64_string = str_replace('+', '.', $base64_string);
// Truncate string to the correct length
$salt = substr($modified_base64_string, 0, $length);
return $salt;
}
function password_check($password, $existing_hash) {
// existing hash contains format and salt at start
$hash = crypt($password, $existing_hash);
if ($hash === $existing_hash) {
return true;
} else {
return false;
}
}
function attempt_login($username, $password) {
$admin = find_admin_by_username($username);
if ($admin) {
// found admin, now check password
if (password_check($password, $admin["password"])) {
// password matches
return $admin;
} else {
// password does not match
return false;
}
} else {
// admin not found
return false;
}
}
?>
<?php
if (isset($_POST['submit'])) {
// Process the form
// validations
$required_fields = array("username", "password");
validate_presences($required_fields);
if (empty($errors)) {
// Attempt Login
$username = $_POST["username"];
$password = $_POST["password"];
$found_admin = attempt_login($username, $password);
if ($found_admin) {
// Success
// Mark user as logged in
$_SESSION["admin_id"] = $found_admin["id"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("MyAccount.php");
} else {
// Failure
$_SESSION["message"] = "Username/password not found.";
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>