当我尝试使用password_hash
和password_verify
登录时,似乎始终返回false。
这是我的代码。
<-----Login page---->
<?php
require_once '../../includes/initialize.php';
if($session->is_logged_in()){
redirect_to("index.php");
}
if (isset($_POST['submit'])){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//Check database to see if username/password exist.
$found_user = User::authenticate($username, $password);
if ($found_user) {
$session->login($found_user);
log_action('Login', "{$found_user->username} logged in.");
redirect_to("index.php");
}else{
$message = "Username/Password combination incorrect.";
}
}else{
$username = "";
$password = "";
}
?>
<---Create New Admin Page-->
<?php
require_once '../../includes/initialize.php';
if(!$session->is_logged_in()){redirect_to("login.php");}
?>
<?php
if(isset($_POST['submit'])){
$required_fields = array("first_name", "last_name", "username", "password", "confirm_password");
validate_presences($required_fields);
if (empty($errors)) {
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$confirm_password= trim($_POST['confirm_password']);
if ($password != $confirm_password) {
$message = "Passwords does not match!";
}else{
$hashed_password = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
$user = new User();
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->username = $username;
$user->password = $hashed_password;
if($user->create()){
$session->message("Admin {$user->username} created successfully.");
redirect_to('manage_admins.php');
}else {
$message = "Admin can't be created!";
}
}
}
}else{
$first_name = "";
$last_name = "";
$username = "";
}
?>
<------User Object Page ----->
<?php
require_once (LIB_PATH.DS.'database.php');
class User extends DatabaseObject{
protected static $table_name = "users";
protected static $db_fields = array('id', 'username', 'password', 'first_name', 'last_name');
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public function full_name(){
if(isset($this->first_name) && isset($this->last_name)){
return $this->first_name." ".$this->last_name;
}else{
return "";
}
}
public static function authenticate($username="", $password=""){
global $database;
$username = $database->escape_value($username);
$password = $database->escape_value($password);
$sql = "SELECT * FROM users WHERE username = '{$username}' LIMIT 1";
$result_array = self::find_by_sql($sql);
$admin = !empty($result_array) ? array_shift($result_array) : false;
if ($admin) {
//Found Admin Now check password
if (password_verify($password, $admin->password)) {
return $admin;
}else {
return false;
}
}
}
}
?>