Reputation:
require_once "require.php";
$con = new mysqli($hn,$un,$pas,$db);
if ($con->connect_error)
{
die("Unbale to connect to the Server");
}
if (isset($_POST["login"]))
{
$uname = $_POST["uname"];
$lpass = $_POST["lpass"];
$query = "SELECT PASSWORD FROM users WHERE username='$uname'";
$result = $con->query($query);
$dpass = $result->fetch_assoc()['password'];
if ($dpass==$lpass)
{
echo "Passwords Match";
}
}
I'm trying to match the password that the user has entered and the one in the database, I don't know if the way i have used is the right way of getting the password, any help would be appreciated.
Upvotes: 0
Views: 70
Reputation: 566
Please read the comments. Password in plain text are really no good idea). I answer you just on learning purpose. Don't do this in real live production!
But to go on your code. $result->fetch_assoc()
returns an Array. So you have to loop over it or address it right. This example expects a result from the query. So you have to check there is a result, else you'll get an error.
Take a look at your Query LIMIT 1
and
$result->fetch_assoc()
and then the $dpass[0]['password']
<?php
require_once "require.php";
$con = new mysqli($hn, $un, $pas, $db);
if ($con->connect_error) {
die("Unbale to connect to the Server");
}
if (isset($_POST["login"])) {
$uname = $_POST["uname"];
$lpass = $_POST["lpass"];
// LIMIT1
$query = "SELECT passwordFROM users WHERE username='$uname' LIMIT 1";
$result = $con->query($query);
// fetch all
$dpass = $result->fetch_assoc();
// Check there is 1 result
if ($result->num_rows == 1) {
// check your password
if ($dpass == $lpass[0]['password']) {
echo "Passwords Match";
} else {
echo "Wrong Password";
}
// No User match
} else {
echo "No User foound";
}
} else {}
I didn't try the example, but it should work.
Read more about that:
Upvotes: 1
Reputation: 371
require_once "require.php";
$con = new mysqli($hn,$un,$pas,$db);
if ($con->connect_error)
{
die("Unbale to connect to the Server");
}
if (isset($_POST["login"]))
{
$uname = $_POST["uname"];
$lpass = $_POST["lpass"];
$query = "SELECT PASSWORD FROM users WHERE username='$uname'";
$result = $con->query($query);
$dpass = $result->fetch_assoc()['password'];
$newhash = password_hash($dpass, PASSWORD_DEFAULT);
if (password_verify($lpass, $newhash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
}
Try like this... password verify is a better practice
Upvotes: 1
Reputation: 794
You can use password_hash() to generate and can use password_verify() to verify the password.
Note: Always keep habit of validating, sanitizing and escaping every data from third party. You can take concepts from this WordPress article on this topic https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data https://vip.wordpress.com/2011/10/13/key-differences-between-validation-and-sanitization/
Thanks
Upvotes: 0