Comparing MYSQL password vs HTML form password - php

I have a Login form with UserId and Password.
I guess the problem is with md5 password in the mysql database.so How to compare HTML form password with mysql password.??
here is the code for the login form
<body>
<form method="post" action="validate_login.php" >
<table border="1" >
<tr>
<td><label for="LoginID">LoginID</label></td>
<td><input type="text"
name="LoginID" id="LoginID"></td>
</tr>
<tr>
<td><label for="password">password</label></td>
<td><input name="password"
type="password" id="password"></input></td>
</tr>
<tr>
<td><input type="submit" value="Submit"/>
<td><input type="reset" value="Reset"/>
</tr>
</table>
</form>
</body>
And the php code :
<?php
// Grab User submitted information
$LoginID = $_POST["LoginID"];
$password = $_POST["password"];
//$UserID= $_POST["UserID"];
// Connect to the database
$username = "avaninfo_dairy";
$password = "CMANcustomersupportsystem1234#";
$hostname = "localhost";
//connection to the database
$con = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Select the database to use
mysql_select_db("avaninfo_dairy",$con);
$result = mysqli_query("SELECT * FROM cman_users WHERE LoginID = $LoginID");
$row = mysqli_fetch_array($result);
if($row["LoginID"]==$LoginID && $row["Password"]== $password)
echo"You are a validated user.";
else
echo"Sorry, your credentials are not valid, Please try again.";
?>

The way to do this would be to md5 encode using the same salt the password from the user and check it against the md5 hash stored on the database. http://php.net/md5

Use the md5 function
$row = mysqli_fetch_array($result);
if($row["LoginID"]==$LoginID && $row["Password"]== md5($password))
echo"You are a validated user.";
else
echo"Sorry, your credentials are not valid, Please try again.";

Use MD5 built in function:
if($row["LoginID"]==$LoginID && $row["Password"]== MD5($password))
echo"You are a validated user.";
else
echo"Sorry, your credentials are not valid, Please try again.";

(Assuming you want to compare an unhashed password to an md5 hashed password.)
Change $row["Password"] == $password to $row["Password"] == md5($password).
$row = mysqli_fetch_array($result);
if($row["LoginID"]==$LoginID && $row["Password"]== md5($password))
echo"You are a validated user.";
else
echo"Sorry, your credentials are not valid, Please try again.";
More info on md5: http://php.net/manual/en/function.md5.php
P.S. - If it is within your control, I recommend that you use password_hash() and password_verify() to hash your passwords.
It is much securer than md5().

You can use the md5 function. Also you do not need to check the LoginID because the SQL Select prefilters.
if($row["Password"]== md5($password))
However the overall security system is wrong. The web browser should send username and md5(password). The password should never be sent over the internet.
Also, the MD5 hash has been proven to be hackable. Use SHA-1 hash at a minimum.
And most systems Salt the Hash so that the same password for different users have a different hash value in the database.

<?php
// Grab User submitted information
$LoginID = $_POST["LoginID"];
$password = md5($_POST["password"]);
//$UserID= $_POST["UserID"];
// Connect to the database
$username = "avaninfo_dairy";
$password = "CMANcustomersupportsystem1234#";
$hostname = "localhost";
//connection to the database
$con = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
// Select the database to use
mysql_select_db("avaninfo_dairy",$con);
$result = mysqli_query("SELECT * FROM cman_users WHERE LoginID = $LoginID" and Password=$password);
$row = mysqli_num_row($result);
if($row>0)
echo"You are a validated user.";
else
echo"Sorry, your credentials are not valid, Please try again.";
?>
Try this one it will be work fine

The answer is simple. To have some clarity first you need to get an idea of whats going on.
Your MD5 Hashing algorithms which is stored in your database
"md5 password in the mysql database"
are one way. That means you cannot "undo" it once its encrypted. What you can do is compare a hashed value to it to see if it matches.
How to compare HTML form password with mysql password.??
this will compare the html form password with mysql password,
$hashed_value_from_mysql being your encrypted password from mysql and
$_POST[password] being your password from the form submission
where your name="password" is accessible through $_POST after
you submit the form depending on which method you use.
if ($hashed_value_from_mysql === md5('$_POST[password]')) {
//if the password matched do whatever here
} else {
//it doesn't match, throw an error
echo "password doesn't match";
}

Related

password_verify() not verifying hashed password

I'm trying to has a password in PHP using password_hash and password_verify. I am correctly hashing the password as it is being into the database hashed, but when I attempt to unhash the password whilst logging in, it doesn't seem to want to work. The password is being recieved from an Android application but after echoing both the username and the password, they are correct to what they should be. To hash the password, I am using PASSWORD_DEFAULT as the hashing technique.
Code:
<?php
error_reporting(0);
require_once('dbconnect.php');
$username = $_POST["username"];
$password = $_POST["password"];
$result = $conn->query("SELECT * FROM User WHERE username ='$username'");
if(empty($result)){
die("Username doesn't exist");
}
$dbpass = $conn->query("SELECT password FROM User WHERE username = '$username'");
if (password_verify($password, $dbpass)){
$stmt = "SELECT * FROM User WHERE username='$username' and password='$password'";
$check = mysqli_fetch_array(mysqli_query($conn, $stmt));
if(isset($check)){
echo "success";
}else{
echo "Invalid Username or Password";
}
}
else {
echo "password not unhashing";
}
$conn->close();
Am I missing something obvious?
First, use prepared statements to remove the threat of SQL injection, or your login screen becomes an attack vector. Then the problem is you're not getting the actual dbpass, you're getting a result set containing $dbpass, without dereferencing it.
Try it this way:
//username in where clause is coming from the user, don't execute it
//also fetch a clean copy of the username from the database we can trust to do things with like display -- assuming we filtered it on the way into the database.
$stmnt = $conn->prepare('select username,password from user where username = ?') or die('...');
//username must be a string, and to keep it clear it came from a user, and we don't trust it, leave it in POST.
$stmnt->bind_param('s',$_POST['username']) or die('...');
//Do the query.
$stmnt->execute() or die('...');
//Where to put the results.
$stmnt->bind_result($username,$dbpass);
//Fetch the results
if($stmnt->fetch()) //get the result of the query.
{
if(password_verify($_POST['password'],$dbpass))
{
//The password matches.
}
else
{
//password doesn't match.
}
}
else
{
//username is wrong.
}

Q: Edit New Password PHP Mysql

Somebody help me with my code. I create a edit password page containing the Current Password, New Password and Confirm Password. Here's my code:
edit_password.php
<form action="editpassword_process.php" method="post">
<table>
<tr class="form-group has-feedback has-success">
<td><h4>Current Password</h4></td>
<td><div class="control-group input-lg"><input type="password" placeholder="" passfield="true" id="currentpassword" name="currentpassword"></div></td> <!-- class="input-sm" required -->
<td><span id="messagebox"></span></td>
</tr>
<tr>
<td><h4>New Password</h4></td>
<td><div class="control-group input-lg"><input type="password" placeholder="" passfield="true" id="newpassword1" name="newpassword1"></div></td> <!-- required class="input-sm" -->
</tr>
<tr>
<td><h4>Confirm Password</h4></td>
<td><div class="control-group input-lg"><input type="password" placeholder="" passfield="true" id="newpassword2" name="newpassword2" onKeyUp="checkPass(); return false;"></div></td> <!-- required class="input-sm" -->
<span id="confirmMessage" class="confirmMessage"></span>
</tr>
</table>
<button class="btn btn-info">Submit</button>
</form>
Here's my code of editpassword_process.php
<?php
include('connection.php');
$currentpw = $_POST['currentpassword'];
$newpw = $_POST['newpassword1'];
$confirmnewpw = $_POST['newpassword2'];
$res = mysql_query("SELECT user_password FROM `tbl_userlist` WHERE userid = '".$_SESSION['userid']."'");
if($currentpw != mysql_result($res, 0)){
echo "You entered an incorrect password";
}
if($newpw = $confirmnewpw){
$sql = mysql_query("UPDATE tbl_userlist SET user_password = '$newpw' WHERE userid = '".$_SESSION['userid']."'");
}
if($sql){
echo "You have successfully changed your password";
}
else{
echo "The new password and confirm pasword fields must be the same";
}
?>
When i click the submit it appears an alert that shows Validated OK but my database didn't update.
Thank you in advance
There are a few things wrong with your code, but I'll start with why your user password isn't updating. You haven't started a session anywhere in your code. Anywhere you use sessions, you need to start them with:
session_start();
This should be the very first thing you do after your opening <?php tag.
You're assigning(=) and not comparing (==) in a lot of your if(){.. comparison blocks, these will evaluate to TRUE, running the condition.
Now on to the bad, you're using a deprecated library. All mysql_* functions are deprecated and removed as of PHP7. It's best to get ahead of the curve-ball by learning either of these 2 libraries:
PDO
MySQLi Prepared Statements
Either of them will mitigate any SQL Injections you'd come across with your currently vulnerable code. Not to mention the fact that you're storing passwords in plain text. Imagine the implications when (not if) your database is hacked, I hope this isn't a production environment.
PHP makes it super simple to hash a password, just check out:
password_hash()
password_verify()
They'll sort out your password hashing.
To simplify what you're doing, this would be a PDO example along with hashing of your passwords to show you how simple it is to achieve what you're trying to do:
<?php
session_start();
include('connection.php');
$currentpw = $_POST['currentpassword'];
$newpw = $_POST['newpassword1'];
$confirmnewpw = $_POST['newpassword2'];
// start your PDO object
$db = new PDO('mysql:host=localhost;dbname=DATABASE', 'username','password');
$statement = $db->prepare("SELECT user_password FROM `tbl_userlist` WHERE userid = :userid");
$statement->execute(array(':userid' => $_SESSION['userid']));
// check if we have a row
if ($statement->rowCount() > 0) {
$data = $statement->fetch(PDO::FETCH_ASSOC);
$current_password_hash = $data['user_password'];
// check current password is correct.
if (!password_verify($currentpw, $current_password_hash)) {
// wrong "current" password.
die("You entered an incorrect password");
}
// check that both passwords match.
if (trim($confirmnewpw) !== trim($newpw)) {
// new passwords dont match
die("The new password and confirm pasword fields must be the same");
}
// can only get here if passwords match.
// so hash the new password and store in the database.
$newpwhash = password_hash(trim($confirmnewpw), PASSWORD_BCRYPT, array('cost' => 11));
// now lets update table to add new password hash.
$update = $db->prepare("UPDATE tbl_userlist SET user_password = :newpwhash WHERE userid = :userid");
if($update->execute(array(':newpwhash' => $newpwhash, ':userid' => $_SESSION['userid']))) {
// password updated successfully.
die("You have successfully changed your password");
} else {
// failed to update, check logs to ammend.
die('Failed to update password.');
}
} else {
// wrong "current" password.
die("No password found for you...");
}
Needless to say, this will mean you'll have to change your login process too, but it's simple. All you'll need to do is fetch the password and harness password_verify(), and voila, you're sorted.
(Not to mention, a ton more secure.)
Change following things
<?php
session_start(); // Start session as you are using it
include('connection.php');
$currentpw = $_POST['currentpassword'];
$newpw = $_POST['newpassword1'];
$confirmnewpw = $_POST['newpassword2'];
$res = mysql_query("SELECT user_password FROM `tbl_userlist` WHERE userid = '".$_SESSION['userid']."'");
if($currentpw != mysql_result($res, 0)){
echo "You entered an incorrect password";
}
if($newpw = $confirmnewpw){ // Compare using == or ===
$sql = mysql_query("UPDATE tbl_userlist SET user_password = '$newpw' WHERE userid = '".$_SESSION['userid']."'");
// mysql_query("UPDATE tbl_userlist SET user_password = '$newpw' WHERE userid = '".$_SESSION['userid']."'", $connectionVar);
}
if($sql){ // Here You have not executed the query now use $connection->query($sql)
// OR mysql_query($connection,$sql); any other
echo "You have successfully changed your password";
}
else{
echo "The new password and confirm password fields must be the same";
} ?>
when you running this code :
"UPDATE tbl_userlist SET user_password = '$newpw' WHERE userid = '".$_SESSION['userid']."'"
that's mean you update tbl_userlist with criteria userid from session. value from session can be used if you start the session using code session_start();

PHP hash SHA256 login password (different from normal)

This is my function to hash password on registration page.
function hashPassword($orgPassword){
srand(date("s"));
$chars = "abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$salt = "";
$num = strlen($chars);
for($i=0;$i<15;$i++){
$salt.= $chars[rand()%$num];
}
$hashedPassword = "\$SHA\$".$salt."\$".hash('sha256',hash('sha256',$orgPassword).$salt);
return $hashedPassword;
}
This is my php for login.
<?php
$username = $_POST['user_name'];
$password = $_POST['user_password'];
$salt = "";
$hashed = "\$SHA\$".$salt."\$".hash('sha256',hash('sha256',$password).$salt);
$con=mysqli_connect("127.0.0.1", "root", "mypassword", "testdb");
if (mysqli_connect_errno($con)){
echo "MySql Error: " . mysqli_connect_error();
}
$query=mysqli_query($con,"SELECT * FROM user WHERE user_name='$username' && user_password='$hashed'");
$count=mysqli_num_rows($query);
$row=mysqli_fetch_array($query);
if ($count==1){
echo "success";
}else {
echo "Invaild Username Password";
}
mysqli_close($con);
?>
But login.php always give me "Invaild Username Password".
Thank you reading If you want to know more detail please ask because I'm not very well to explain in English.
I'm Thai but I will try to explain as best as I can.
You have an empty $salt in your login. The strings arent equal.
Additionally, you'd be better off using crypt(). Get the stored password based on the users name and compare the stored hash that way.
Why don't you write $hashed=hashPassword($password) to hash the user input?
EDIT: Your function uses random numbers and will generate a different hashed code everytime. To fix this, you should probably use inbuilt hash functions like sha512(). You can find a list of such functions here.

How to login from data from mysql with sha512 hashed password via mysql login?

I have a register system set up that hashes registered passwords to sha512. I don't know how to make it login with this type of hashed password. here's my code:
<?php
$host="localhost";
$username="root";
$password="";
$db_name="users";
$tbl_name="users";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$username=$_POST['username'];
$password=$_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
session_register("username");
session_register("password");
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>
This is really bad:) Read up on SQL injection and why you shoudl use prepared statements instead.
It's strange that you ask how to use the code you've written...
When you sha a string you encrypt it so if you have the sha'd password in the database you simply can't compare them.
You need to ask the user for their password, then create a new string from that that is also sha's and then compare them. SOmething like:
get user password from form
shaPass = hash('sha512', $userInputFromForm);
if(shaPass == passwordFromDatabase){
return true;
}else{
return false;
So, you need a form, you need to ask the user for thier username or email address, whatever it is you've chose and ask them for their password.
In the example above, (which you really should change) you would create the shaPass as I mentioned above and then test the conditions in the database.
If (usernameFromForm == usernameFromDatabase) && (shaPass == passwordFromDatabase){
login = true;
set session data;
redirect to home page
}else{
error etc}
You should get the idea from that
$hashed = hash('sha512', $password);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$hashed'"
You will need to compare the entered password with the hashed password in the database.
To do that you hash the entered password too. If the password is valid the hash should be the same as in the database.
So just add
$password = hash('sha512', $password);
Before the query.
use hash() function
$password = hash('sha512', $password);
and check if sha512 available using hash_algos():
print_r(hash_algos());

Implement crypt() in php

I am trying to encrypt the given password to match one that is in a database. However using crypt() gives me a different result each time so it never matches. How can i make this work.
here is the statement that hashes the password given by the user.
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = crypt($_POST['password']);
prior to this i manually made a user that had the crypt('password') but if I enter 'password' into the field it doesn not match.
Try below:
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// get the hashed password from database
$hashed_password = get_from_db($username);
if (crypt($password, $hashed_password) == $hashed_password) {
echo "Password verified!";
}
}
Try like this,
//$pass_entered_from_login is the user entered password
//$crypted_pass is the encrypted password from the
//database or file
if(crypt($pass_entered_from_login,$crypted_pass)) == $crypted_pass)
{
echo("Welcome to my web site.")
}
Read more
crypt auto generates the salt each time you use it ............
so use the same salt for the user
do this while registering the user to your database and while checking tooo.
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = crypt($_POST['password'],$_POST['username']);
}
NOTE: the 2nd parameter is the salt in crypt function .
hope it helps :)

Categories