[英]Cant login with the right password in PHP PDO
I am building a simple register/login app with php PDO, and when i register and try to login with the right password, the password error just keeps coming.我正在使用 php PDO 构建一个简单的注册/登录应用程序,当我注册并尝试使用正确的密码登录时,密码错误不断出现。 What could be wrong here?
这里可能有什么问题?
if ($stmt->execute()) {
if ($stmt->rowCount() === 1) {
if ($row = $stmt->fetch()) {
$hashed_password = $row['password'];
if (password_verify($password, $hashed_password)) {
session_start();
$_SESSION['email'] = $email;
$_SESSION['username'] = $row['username'];
header('location: index.php');
} else {
$password_err = 'The password you entered is not valid';
}
}
} else {
$email_err = 'No account found for that email';
}
} else {
die('Something went wrong');
}
}
and here is the part of the register.php file:这是 register.php 文件的一部分:
$password = password_hash($password, PASSWORD_DEFAULT);
$sql = 'INSERT INTO users (username, email, password) VALUES (:username, :email, :password)';
if($stmt = $pdo->prepare($sql)){
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
if($stmt->execute()){
header('location: login');
} else {
die('Error');
}
}
If i were you i would create a class for user like this如果我是你,我会为这样的用户创建一个类
class User{
public static function Login($data){
$_SESSION['user_id']=$data['user_id'];
$_SESSION['username']=$data['username'];
}
after that i would create post and get functions for all of my project之后,我将为我的所有项目创建帖子并获取功能
function post($name)
{
if (isset($_POST[$name])){
if (is_array($_POST[$name]))
return array_map(function($item){
return htmlspecialchars(trim($item));
}, $_POST[$name]);
return htmlspecialchars(trim($_POST[$name]));
}
}
function get($name)
{
if (isset($_GET[$name])){
if (is_array($_GET[$name]))
return array_map(function($item){
return htmlspecialchars(trim($item));
}, $_GET[$name]);
return htmlspecialchars(trim($_GET[$name]));
}
}
and i would create a function for control my forms我会创建一个函数来控制我的表单
function form_control(...$except_these){
unset($_POST['submit']);
$data = [];
$error = false;
foreach ($_POST as $key => $value){
if (!in_array($key, $except_these)&& !post($key)){
$error = true;
}else {
$data[$key] = post($key);
}
}
if ($error){
return false;
}
return $data;
}
NOW LOGIN现在登录
if (post('submit')){
if ($data = form_control()){
$row = $db->query("SELECT * FROM users WHERE username = $data['username']")->fetch(PDO::FETCH_ASSOC);
if (!$row){
$error = 'no such user.';
} else {
$password_verify = password_verify($data['password'], $row['password']);
if ($password_verify){
User::Login($row);
header('Location:');
} else {
$error = 'incorrect pass';
}
}
} else {
$error = 'enter your details.';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.