How to select a hashed password from mysql db [duplicate] - php

This question already has answers here:
How do I use password hashing with PDO to make my code more secure? [closed]
(3 answers)
Closed 5 years ago.
Okay, so I'm trying to make a register/login code for my personal website.
I had no troubles making the registration form but I'm having some difficulties with the login.
Here's a part of my code:
$stmt = $pdo->prepare("SELECT password FROM members where username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
Now to my understanding i need to fetch the first row from my table convert it to a string and then using password_verify to compare that string to whatever the users inputs in the form i created. The problem i have is that it fetches an array and can't really use password_verify to compare a string to an array.
Am I doing something wrong? how should I do this?
tl; dr How do I actually select a hashed password from DB, convert it to a string and then compare that string with the password my user will input.
Thanks.

This library works on
PHP 5.5+: use password_hash
$sql = "SELECT * FROM members WHERE username = ?";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}

Related

Unhashed password in PHP [duplicate]

This question already has an answer here:
Verifying password_hash() in PDO prepared statements
(1 answer)
Closed 7 months ago.
how I can put my variable $passHash from register function to login function
I need that cause I try to use password_verify() method which required my hash
I try additional got my hashe password from database and put to the password_verify() but it not working.
public function register($uname, $email, $pass) {
$passHash = password_hash($pass, PASSWORD_DEFAULT);
$sqlQuery="INSERT INTO UserData (userName, userEmail, userPassword) VALUES (:userName,:userEmail,:userPassword)";
$stmt = $this->db->prepare($sqlQuery);
$stmt->bindparam(':userName', $uname);
$stmt->bindparam(':userEmail', $email);
$stmt->bindparam(':userPassword', $passHash);
if($stmt->execute()) {
return true;
} else {
return $stmt->error;
}
}
public function login($emailUser,$passUser){
$sqlQuery= "SELECT * FROM UserData WHERE userEmail=? AND userPassword=? ";
// $sqlQuery.Id;
$stmt = $this->db->prepare($sqlQuery);
$stmt->execute([$emailUser, $passUser]);
$result = $stmt->fetch(PDO::FETCH_ASSOC); <-- NOT WORKING SO I try get hash variable from register function
$checkPassword=password_verify($passUser,$result["userPassword"]);
if($checkPassword==true){
if($stmt->rowCount()==0){
echo "err";
}else{
echo "success";
}
}else{
echo 'bad pass';
}
}
Steps to run a successful login attempt:
Collect the username/identifier from the login client.
$emailUser = $_POST['email'];
$passUser = $_POST['password'];
Send only that to the MySQL to retrieve only that row, including the hashed password and the row identifier.
SELECT UserId, userPassword FROM UserData WHERE userEmail=?
Using PHP check the hashed password from the database matches the value given by the user
if(password_verify($passUser, $result['userPassword']){
...
allow access....
NEVER send the password to MySQL, it's worthless.
Use $stmt->fetchAll(); to retrieve the data row
It is bad practise to do SELECT * instead you should select the columns you actually want to use.
your $stmt->rowCount()==0 clause will always fail, because it is after the password has been tested and passed, so remove this whole section.
It is bad practise to tell people specifically their password has failed, as this can be used to fish for if someone has an email on this system. Instead state "Your email OR password are incorrect" so it can't so easily be established by 3rd parties if a certain persons email is on a system.

Verify hashed passwords using PHP from a MySQL database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to develop a login form using HTML, PHP, and SQL. I'm scratching my head on trying to figure out what my issue is and how to fix it as I'm relatively new to PHP, so I'd appreciate some help. What I want to do is to check if the user's input on the HTML login form (in this case the password) matches the hashed password that is stored inside the database.
However, I'm currently having an issue where it doesn't do that. The code should verify the password and if it is correct, it should echo "password and username match" else it should echo "incorrect password" however the code does not echo anything.
Here is what I've tried:
get password using username
I am using PHP's password_hash plugin to hash and verify the user's password.
So my question is, how do I securely verify the user's input (the password) with the hashed password that is stored inside the database?
Here is the PHP code:
if($_SERVER["REQUEST_METHOD"] == "POST") {
//declare variables and set values to null
$username = $pass = "";
$username = $_POST['username'];
$pass = $_POST['pass'];
//check if username exists
$stmt = $conn->prepare("SELECT userName FROM userDetails WHERE userName=?");
$stmt->bind_param("s", $prepname);
$prepname = $username;
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
//if username exists, check if password is linked to user
echo "user exists";
$stmt = "SELECT userPass FROM userDetails WHERE userName=?";
$stmt->bind_param("s", $prepname);
$prepname = $username;
$hashpass = $stmt->execute();
$stmt->bind_result($hashpass);
$stmt->fetch();
if (password_verify($pass, $hashpass)) {
echo "password and username match";
}
else {
echo "incorrect password";
}
}
else {
echo "That user does not exist!";
return false;
}
}
EDIT: Thanks to #Jovi, I have fixed the previous error however I am now recieving a new error:
Warning: Illegal string offset 'userPass' in /home/toeaimc2/public_html/php/pages/login.php on line 75
EDIT:
#Jovi has now solved the problem! Thank you to everyone for their help!
You are calling the bind_param method on a string, it should be a statement object.
You are missing the method call to create the prepared statement object for the query that extracts the password:
$stmt = $conn->prepare("SELECT userPass FROM userDetails WHERE userName=?");
$stmt->bind_param("s", $prepname);

Verifying a hashed password from database [duplicate]

This question already has answers here:
How to verify_password from a database
(2 answers)
Closed 3 years ago.
So I have a login page which worked fine without hashed passwords but of course, that wasn't secure so I decided to hash the passwords when registering.
but I don't know how and where should I use verify_password when I'm selecting the password from the database. I use while to see if there is a result with the username and password entered like this:
$q = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$x = $conn->query($q);
if ($x->num_rows > 0) {
while ($row = $x->fetch_assoc()) {
//Logged in seccesfully!
}
} else {
// Username or password is wrong!
}
password_hash() function can simplify our lives and our code can be secure. When you need to hash a password, just feed it to the function and it will return the hash which you can store in your database.
$hash = password_hash($password, PASSWORD_DEFAULT);
Now that you have seen how to generate hashes with the new API, let’s see how to verify a password. Remember that you store the hashes in a database, but it’s the plain password that you get when a user logs in.
The password_verify() function takes a plain password and the hashed string as its two arguments. It returns true if the hash matches the specified password.
<?php
if (password_verify($password, $hash)) {
// Success!
}
else {
// Invalid credentials
}
for more info read

How do I pass in a variable with an exclamation mark in it? PHP [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I'm working on a database login system in PHP but one of my users has an exclamation mark in his password which breaks it, The line where it says ($password = $_GET['p'];) is where the password gets passed in
$username = $_GET['u'];
$password = $_GET["p"];
function userLoginIpb($username, $password) { //select the password information froms elected user
$query = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT `members_pass_salt`, `members_pass_hash` FROM `members` WHERE `name` = '$username'");
$results = mysqli_fetch_assoc($query);
$password = md5(md5($results['members_pass_salt']).md5($password));
if ($password == $results['members_pass_hash']) {
return true;
} else {
return false;
}
The issue is your $_GET[] request, since a ! character will be encoded to %21.
Since you're working on the system, do it the correct way instead.
Use POST requests, as you don't want the users to copy paste a link with a password in them.
Use the new functions in PHP, password_hash() with password_verify() as they have a salt build into them making it quite secure and very easy to work with.
Bind values to a SQL string do not blindly put them in there as you are currently open to an easy SQL injection. Adding a password like pass; DROP TABLE members; will break it.
You need to use mysqli_real_escape_string:
<?php
$username = $_GET['u'];
$password = $_GET["p"];
// select the password information froms elected user
function userLoginIpb($username, $password)
{
global $___mysqli_ston;
$s = mysqli_real_escape_string($___mysqli_ston, $username);
$query = mysqli_query($___mysqli_ston, "SELECT `members_pass_salt`, `members_pass_hash` FROM `members` WHERE `name` = '$s'");
$results = mysqli_fetch_assoc($query);
$password = md5(md5($results['members_pass_salt']).md5($password));
return $password == $results['members_pass_hash'];
}
Also take a look at PDO.

Check if randomly generated username is unique [duplicate]

This question already has answers here:
Insert data only if record does not exist
(3 answers)
Closed 9 years ago.
I need to have a system where a random password and username are created for each new user.
As such, I need to make sure the username is unique.
However I cant figure out why the code below isn't working. It isn't a syntax issue. I just can't figure out where I have gone wrong logically.
anyway here is what I have tried:
$Password= randomPassword();
$Username = randomPassword();
$UsernameCheckQuery = mysql_query("SELECT * FROM users WHERE username = '".$Username."'");
while (mysql_num_rows($UsernameCheckQuery ) >= 1) {
$Username = randomPassword();
$UsernameCheckQuery = mysql_query("SELECT * FROM users WHERE username = '".$Username."'");
}
I know this topic appears elsewhere on Stack Overflow and on the web. However every question I have seen has been using an if statement to check if the username is already used. In my case I cant see how an if statement would work as the randomPassword function could generated two username that already exist in a row.
Try
while (true) {
$Username = randomPassword();
$UsernameCheckQuery = mysql_query("SELECT * FROM users WHERE username = '".$Username."'");
if (mysql_num_rows($UsernameCheckQuery ) < 1) {
break;
}
}
echo 'The generated username is '.$Username;

Categories