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. 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:
$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.';
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.