This question already has answers here:
Where to put password_verify in login script?
(2 answers)
Closed 7 years ago.
Okay so i'm trying to make a basic user authentication system. Well I already made it. But what im trying to do now is check the users password against a hash. I'm using $hash = password_hash($password, PASSWORD_DEFAULT); but for the login page I want to check the users password with the hashed password in the database so they can login. How can I do this?
Register.php:
<?php
include('config.php');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function mres($input){
if (get_magic_quotes_gpc()){
$input = stripslashes($input);
}
return mysqli_real_escape_string($conn, $_POST['$input']);
}
$email=mysqli_real_escape_string($conn, $_POST['email']);
$username=mysqli_real_escape_string($conn, $_POST['username']);
$password=mysqli_real_escape_string($conn, $_POST['password']);
$hash = password_hash($password, PASSWORD_DEFAULT);
$query = $conn->query("select * from users where username='$username'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
echo "User already exist redirecting in 5 seconds!";
} else {
$sql = "INSERT INTO users (username, password, email)
VALUES ('$username', '$hash', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
header("Location: ../index.php");
?>
Login.php:
<?php
session_start();
include('config.php');
$error='';
if (isset($_POST['submit'])) {
if (empty($_POST['userid']) || empty($_POST['passid'])) {
$error = "Username or Password is invalid";
}
else
{
$user=mysqli_real_escape_string($conn, $_POST['userid']);
$pass=mysqli_real_escape_string($conn, $_POST['passid']);
$hash = password_hash($pass, PASSWORD_DEFAULT);
$passv = password_verify($pass, $hash);
$query = $conn->query("select * from users where password='$passv' AND username='$user'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username;
$_SESSION['username']=$user;
$_SESSION['checklogin']== true;
header("location: ../profile.php");
} else {
$error = "Username or Password is invalid";
}
mysqli_close($conn);
}
}
?>
(Yes i know i added that function there that im not using in register. Its for future use im saving it for now. I have plans for it.)
Select the password from database using the username. Get the hash password from the database and use password_verify(inputPassword,hashPassword) with an if statement.
Related
I am making a login and registration form and I use password_hash for password encryption, the problem is that when I log in it does not recognize my password and I get the error "the password is incorrect" (a message that I set). In the registration form there are no problems, but maybe it has to do with the error that I have.
Login.php
<?php
include 'connect/config.php';
session_start();
error_reporting(0);
if (isset($_SESSION["user_id"])) {
header('Location: home');
}
if (isset($_POST["signin"])) {
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$password = mysqli_real_escape_string($conn, $_POST["password"]);
$check_email = mysqli_query($conn, "SELECT id FROM users WHERE email='$email' AND password='$password'");
if (mysqli_num_rows($check_email) > 0) {
$row = mysqli_fetch_array($check_email);
$_SESSION["user_id"] = $row['id'];
if (password_verify($password, $row['password'])){
$msg[] = "You have successfully logged in.";
}
header('Location: home');
} else {
$msg[] = "The password or email is incorrect.";
}
}
?>
Now, if I change the $check_email = mysqli_query($conn, "SELECT id FROM users WHERE email='$email' AND password='$password'"); to $check_email = mysqli_query($conn, "SELECT id, password FROM users WHERE email='$email'"); I can enter the home, but with any password and not the one I registered with.
Registration.php
<?php
include 'connect/config.php';
session_start();
error_reporting(0);
if (isset($_SESSION["user_id"])) {
header("Location: home");
}
if (isset($_POST["signup"])) {
$full_name = mysqli_real_escape_string($conn, $_POST["signup_full_name"]);
$email = mysqli_real_escape_string($conn, $_POST["signup_email"]);
$password = mysqli_real_escape_string($conn, $_POST["signup_password"]);
$cpassword = mysqli_real_escape_string($conn, $_POST["signup_cpassword"]);
$token = md5(rand());
$check_email = mysqli_num_rows(mysqli_query($conn, "SELECT email FROM users WHERE email='$email'"));
if ($password !== $cpassword) {
$msg[] = "Passwords do not match";
} elseif ($check_email > 0) {
$msg[] = "The email already exists, try another.";
} else {
$passHash = password_hash($password, PASSWORD_BCRYPT);
$sql = "INSERT INTO users (full_name, email, password, token, status) VALUES ('$full_name', '$email', '$passHash', '$token', '0')";
$result = mysqli_query($conn, $sql);
if ($result) {
header('Location: login');
$_POST["signup_full_name"] = "";
$_POST["signup_email"] = "";
$_POST["signup_password"] = "";
$_POST["signup_cpassword"] = "";
$msg[] = "Registered user successfully.";
} else {
$msg[] = "User registration failed, please try again later.";
}
}
}
?>
I hope you can help me.
Review my code but my low level of knowledge in php prevents me from finding the error, I hope you can do it for me, I will thank you
You should not have and password = '$password' in the query. The password in the database is the hashed password, not the same as $password. You should just fetch the row using the email, then use password_verify() to check the password.
You also need to select the password column so you can verify it.
$check_email = mysqli_query($conn, "SELECT id, password FROM users WHERE email='$email'");
You also have problems with your logic. You set the session variable and redirect to home regardless of the password verification. It should be:
$row = mysqli_fetch_array($check_email);
if ($row && password_verify($password, $row['password'])){
$msg[] = "You have successfully logged in.";
$_SESSION["user_id"] = $row['id'];
header('Location: home');
} else {
$msg[] = "The password or email is incorrect.";
}
You also shouldn't escape the password before hashing or verifying it. And of course, if you correctly use prepared statements with parameters, you shouldn't escape anything first.
This question already has answers here:
How to use PHP's password_hash to hash and verify passwords
(5 answers)
Closed 1 year ago.
I want to encrypt the password and store it in the database but I do not really understand how to use password_hash. I had found some tutorials but it doesn't work.
The below is connnection.php
<?php
$conn = new mysqli("localhost","root","","mydata");
if (!$conn) {
die('Please Check your connection'/mysqli_error($conn));
}
?>
The below is login.php
<?php
require_once('connection.php');
$msg="";
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$password_encrypted = password_hash($password, PASSWORD_DEFAULT);
$sql = "SELECT * FROM login WHERE UserName=? AND Password=? ";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss",$username,$password_encrypted);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
session_regenerate_id();
$_SESSION['username'] = $row['UserName'];
session_write_close();
if($result-> num_rows==1 && $_SESSION['username']=="admin")
{ header("location:home.php"); }
else{ $msg = "Username or Password is Incorrect!!!";}
}
?>
Try the below code for verifying password
<?php
require_once('connection.php');
$msg="";
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$password_encrypted = password_hash($password, PASSWORD_DEFAULT);
$sql = "SELECT * FROM login WHERE UserName=? ";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss",$username);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($result->num_rows > 0) {
while($row){
if(password_verify($row['password'], $password_encrypted)) {
session_regenerate_id();
$_SESSION['username'] = $row['UserName'];
session_write_close();
if ($_SESSION['username']=="admin") {
$msg = "Login successfully!!!";
header("location:home.php");
}else{
$msg = "Login successfully!!!";
header("location:user.php");
}
}else{
$msg = "Username or Password is Incorrect!!!";
}
}
}else{
$msg = "Username or Password is Incorrect!!!";
}
}
?>
I have admin page that will insert user id, password, role. The password will be hash after admin insert new user. It work well but when I try to login using the hash password, it will pop up "invalid user or password". Maybe because I put the password_verify coding in the wrong place. Can someone help me!!
Below is my coding
login.php
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "root", "","company");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query($connection, "select * from login where password='$password' AND username='$username'");
$row=mysqli_fetch_assoc($query);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$pwdCheck = password_verify($password,$row['password']); $_SESSION['user']=array(
'username'=>$row['username'],
'password'=>$row['password'],
'role'=>$row['role']
);
$role=$_SESSION['user']['role'];
//Redirecting User Based on Role
switch($role){
case 'user':
if ($pwdCheck == true)
header("location: index.php"); // Redirecting To Other Page
break;
case 'admin':
if ($pwdCheck == true)
header("location: adminindex.php"); // Redirecting To Other Page
break;
}
}
else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}
?>
crud_include.php (admin insert new user)
if (isset($_POST['save'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$role = $_POST['role'];
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_query($db, "INSERT INTO login (username, password,role) VALUES ('$username', '$hashedPwd','$role')");
$_SESSION['message'] = "Successfully saved!";
header('location: crud.php');
}
the database (the hash work well but i cannot login using this user
Change your select query : In a where case use only username
<?php
$username=$_POST['username'];
$password=$_POST['password'];
$query = mysqli_query($connection, "select * from login WHERE username='$username'");
$row=mysqli_fetch_assoc($query);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
if (password_verify($password, $row['password'])) {
echo 'Password is valid!';
if($role=$_SESSION['user']['role'] == 'user'){
header("location: index.php");
}elseif($role=$_SESSION['user']['role'] == 'admin'){
header("location: adminindex.php");
}
} else {
$error = "Password is invalid";
}
}else{
$error = "Username is invalid";
}
?>
Hope it will help you.
Here the the link for the hash password verified
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 5 years ago.
I would like to check for duplicates in a MySQL database when registering an user.
If the user exists display an error to that effect, else sign up.
I know there's a few questions like this but I found it hard to paste any of them into my code.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//two passwords are the same
if($_POST['password'] == $_POST['confirmedpassword']) {
$username = $mysqli->real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$sql = "INSERT INTO members(username, password)"
. "VALUES ('$username','$password')";
//if query is successful redirect to login.php
if ($mysqli->query($sql) === true)
$_SESSION['message'] = 'Success';
header("location: login.php");
} else {
$_SESSION['message'] = "User couldnt be added";
}
} else {
$_SESSION['message'] = "Passwords dont match";
}
}
I added some salt to your md5 password to make it seem more secure, but actually this solution is not secure either. To encrypt passwords in PHP it is advisable to use the password_hash() function like this:
$pass = password_hash($password, PASSWORD_BCRYPT);
password_hash() creates a new password hash using a strong one-way hashing algorithm.
and later test it with password_verify():
password_verify ( $passToTest , $knownPasswordHash );
more the functions here: http://php.net/password-hash, http://php.net/password-verify.
Also, since you are using MySQLi consider using prepared statements, or at least properly filter your input data before applying it to the database.
More on prepared statements: http://php.net/prepared-statements.
I added a select statement to check if the user already exists in the table prior to adding the user to the database.
When using header() to change page location put exit() or die() in the next line of code if you want to exit immediately and don't want other code to execute.
Here is your code with the addition of the select statement:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
//two passwords are the same
if($_POST['password'] == $_POST['confirmedpassword'])
{
$username = $mysqli->real_escape_string($_POST['username']);
// You might consider using salt when storing passwords like this
$salt = 'aNiceDay';
$password = md5(md5($_POST['password'].$salt).$salt);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$sql = "SELECT `username` FROM members WHERE `username` = '".$username."'";
$result = $mysqli->query($sql);
if(mysqli_num_rows($result) > 0)
{
echo 'User exists.';
// Do something.
}
else
{
$sql = "INSERT INTO members(username, password) VALUES ('".$username."','".$password."')";
if($mysqli->query($sql) === true)
{
$_SESSION['message'] = 'Success';
header("location: login.php");
// Important to put exit() after header so other code
// doesn't get executed.
exit();
}
else
{
$_SESSION['message'] = "User couldn't be added";
echo "User couldn't be added.";
}
}
}
else
{
$_SESSION['message'] = "Passwords dont match";
}
}
?>
So you can check that the user exists or not.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//two passwords are the same
if($_POST['password'] == $_POST['confirmedpassword']) {
$username = $mysqli->real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
//Check user
$CheckUserIsExist = mysqli->query("SELECT uid FROM members WHERE username='$username'");
if(mysqli_num_rows($CheckUserIsExist)==0 ){
$sql = "INSERT INTO members(username, password)"
. "VALUES ('$username','$password')";
//if query is successful redirect to login.php
if($mysqli->query($sql) === true)
$_SESSION['message'] = 'Success';
header("location: login.php");
}
} else{
echo 'This username is already in use. Please use different username';
}
else{
$_SESSION['message'] = "User couldn't be added";
}
}
else{
$_SESSION['message'] = "Passwords don't match";
}
signup.php
$password_unencrypted = $_POST['passwd'];
$password=md5($password_unencrypted);
$query = "INSERT INTO Customers (firstname, lastname, username, password, " . "gender,mobile,email) " . "VALUES ('$first_name', '$last_name', '$user_name', '$password', " . " '$gender','$mobile','$email')";
Login.php
$username=$_POST['username'];
$password=md5($_POST['password']);
$sql = ("select * from Customers where username='".$username."' and password='".$password."'") or die('Error connecting to MySQL server.');
$query = mysqli_query($con,$sql);
$result=mysqli_fetch_row($query);
if($result)
{
$_SESSION['username']=$username;
header('location:home.html');
}
else
{
echo md5($_POST['password']);
echo 'Your entered username or password is incorrect';
}
In above signup and login codes I'm applying md5 for password storing
I checked in Database the md5 password is storing correctly but is not retreiving properly(i think)
trying to login into page it is failing
FYI : echo md5($_POST['password']); in Login.php is showing same password stored in database
here is it how to fix your login.php code
you were totally checking wrong you need to check first if the query succeeded running then check if returned rows are more than 0 that means the username is correct and we proceed to password checking if everything is fine we start the session assuming you have session_start() on top of your page if not add it before $_SESSION['username'] = $username;
check the manual for password_hash() and password_verify()
on register.php modify saving the password into the database
$password = md5($_POST['password']); to $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
<?php
if isset($_POST['submit']) {
$username= mysqli_real_escape_string($con, trim($_POST['username']));
$password = trim($_POST['password']); // no need to sanitize the password
$sql = "select * from Customers where username = '" .$username."' "; // you don't need or Die() it's just a string
if ($result = mysqli_query($con,$sql)) //check if the Query succeeded running
{
$count = mysqli_num_rows($result);
if($count > 0 )
{ // if username exists we proceed to checking password
$fetch = mysqli_fetch_assoc($result);
$hashedpassword = $fetch["password"];
if ( password_verify($password, $hashedpassword) )
{ //checking password
$_SESSION['username']=$username;
header('location:home.html');
exit;
}else {
echo "incorrect username or password"; // you don't want to tell him that the username is fine but the password is not correct
}
} else {
echo "incorrect username or password";
}
} else {
echo 'Query failed to run';
}
}
?>