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';
}
}
?>
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.
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 username and password matches the database values
(3 answers)
Closed 11 months ago.
I have made a simple login system. Whenever user login password is hashed with password_hash() algorithm and sent to database. But the login page doesnot match the input password with database hashed password by dehashing.
For example :
Username = john & Password = doe
In above example "doe" is hashed and sent to database and the login page
does not login user with the password "doe",user can login with the hashed password directly.
My code is shown below :
signup.php
<?php
date_default_timezone_set('Asia/Kathmandu');
$time = date("h:i:s");
$date = date("Y-d-m");
$con = mysqli_connect("localhost", "root", "", "classic") or DIE("Error!");
if(isset($_POST['submit'])){
$fname=mysqli_real_escape_string($con, $_POST['fname']);
$lname=mysqli_real_escape_string($con,$_POST['lname']);
$uname=mysqli_real_escape_string($con,$_POST['uname']);
$psw=mysqli_real_escape_string($con,$_POST['psw']);
$email=mysqli_real_escape_string($con,$_POST['email']);
$dob=mysqli_real_escape_string($con,$_POST['dob']);
$pswhash = password_hash("$psw", PASSWORD_DEFAULT);
$unique_email = "SELECT * FROM `users` where email='$email'";
$unique_emailresult = mysqli_query($con, $unique_email);
if(mysqli_num_rows($unique_emailresult)>0)
{
echo "Email already exist, try different Email.";
header("refresh:2; url=http:../signup");
}
else{
$unique_user = "SELECT * FROM `users` where username='$uname'";
$unique_userresult = mysqli_query($con, $unique_user);
if(mysqli_num_rows($unique_userresult)>0)
{
echo "Username already exist, try different username.";
header("refresh:2; url=http:../signup");
}
else{
$sql= "INSERT INTO users (firstname, lastname, username, password, email, dob, joindate, jointime) VALUES ('$fname','$lname','$uname','$pswhash','$email', '$dob', '$date', '$time')";
$result=mysqli_query($con, $sql);
if(!$result)
{
die("Error:");
}
echo"New account created successfully, Please Login.";
header("refresh:2; url=http:../login.php");
}
}
}
else{
header("refresh:0; url=http:../login.php");
}
?>
login.php
<?php
session_start();
if(isset($_SESSION['user'])){
header("location:index.php");
}
include_once('Db/dbconnect.php');
#user verification starts
if(isset($_POST['login'])){
$uname = mysqli_real_escape_string($con, $_POST['uname']);
$email = mysqli_real_escape_string($con, $_POST['uname']);
$psw = mysqli_real_escape_string($con, $_POST['psw']);
$sql="SELECT * FROM users WHERE (username='$uname' OR email='$uname') AND password='$psw'";
$result= mysqli_query($con,$sql) or die(mysqli_errno());
$trws= mysqli_num_rows($result);
if($trws==1){
$rws= mysqli_fetch_array($result);
$_SESSION['user']=1;
$_SESSION['username']=$rws['username'];
$_SESSION['password']=$rws['password'];
header("location:index.php?username=$uname&request=login&status=success");
}
else{
echo"Username and password does not matched";
}
}
?>
when you hash the password the first time (when the user registers), you store resulting hash in the database.
$hash_pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
$sql = "INSERT INTO users (id, full_name, email, password, username, sign_up_date, activated) VALUES ('', '$full_name', '$email', '$hash_pass', '$username', '$date', '1')";
The second time (when they try to log in again), you tries to login you simply get the hash from the database WHERE email = '{$_POST['email']} and then use the password_verify function:
if (!password_verify($_POST['login_password'], $hash_from_database)) { exit; }
Below is password_verify() function this is what you are finding, just pass first variable which is user have entered to login and second one is hashed password you have stored at time of registration, this function will give you bool response.
$check = password_verify( $password, $hashedPasswordFromDatabase );
You can check more details of this function from below link.
http://php.net/manual/en/function.password-verify.php
To fetch and match the saved hashed password and the user login password:
Replace that part in the login file:
$sql="SELECT * FROM users WHERE (username='$uname' OR email='$uname') AND password='$psw'";
$result= mysqli_query($con,$sql) or die(mysqli_errno());
$trws= mysqli_num_rows($result);
if($trws==1){
$rws= mysqli_fetch_array($result);
$_SESSION['user']=1;
$_SESSION['username']=$rws['username'];
$_SESSION['password']=$rws['password'];
header("location:index.php?username=$uname&request=login&status=success");
}
else{
echo"Username and password does not matched";
}
With:
//Select user data based on email/username.
$sql="SELECT * FROM users WHERE (username='$uname' OR email='$uname')";
$result= mysqli_query($con,$sql) or die(mysqli_errno());
$trws= mysqli_num_rows($result);
if($trws==1){
$rws= mysqli_fetch_array($result);
//Verify the hashed password and the username login password.
if( password_verify($psw, $rws['password']) ){
$_SESSION['user']=1;
$_SESSION['username']=$rws['username'];
$_SESSION['password']=$rws['password'];
header("location:index.php?username=$uname&request=login&status=success");
}
}
else{
echo"Username and password does not matched";
}
I have been on here all day and looked at all of the answered wuestions and also looked at tutorials online regarding password hashing. It seems as though I am doing it right and it hashes the password in the database but when I go to login it tells me that the password is incorrect. Here is the script, any help would be greatly appreciated.
Login.PHP
if (isset($_POST['username'])){
//escapes special characters in a string
$username = stripslashes($_REQUEST['username']);
$username = mysqli_real_escape_string($con,$username);
$password = $_REQUEST['password'];
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$hash = $row['password'];
if (password_verify($password, $hash)) {
$_SESSION['username'] = $username;
// Redirect user to index.php
$position = $row['position'];
if ( $position == "freelancer" ){
header("Location: ../freelancer/index.php");
}
elseif ($position == "employer"){
header("Location: ../employer/index.php");
}
}
else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
".$hash." " .$password. "
<br />Click here to <a href='login.php'>Login</a>
</div>";
Register.PHP (Piece of Code that Hashes the Password)
//BEGINNING CODE HERE
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$hashPassword = password_hash($password, PASSWORD_DEFAULT);
$sql_u = "SELECT username FROM users WHERE username='$username'";
$sql_e = "SELECT email FROM users WHERE email='$email'";
$res_u = mysqli_query($con, $sql_u);
$res_e = mysqli_query($con, $sql_e);
if (mysqli_num_rows($res_u) > 0) {
$name_error = "Sorry... username already taken";
}
else if(mysqli_num_rows($res_e) > 0){
$email_error = "Sorry... email already taken";
}
else{
$query = "INSERT INTO users (username, email, password)
VALUES ('$username', '$email', '$hashPassword')";
$results = mysqli_query($con, $query);
mkdir("../profilePics/" . $username);
echo 'You Have Registered Successfully!<br>
To Login Go To Our Login Page
';
exit();
}
}
?>
I know there may be more things wrong with this code But I am only interested in getting a basic understanding of password hashing.
$password = mysqli_real_escape_string($con,$password);
You password is now escaped and it certainly won't match the hash.
Better remove this line and look for a better way to ensure the string is safe.
What does escape means?
if your password contains "
it will turns into \"
FYI
Should I mysql_real_escape_string the password entered in the registration form?
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.