This question already has answers here:
How do you use bcrypt for hashing passwords in PHP? [duplicate]
(11 answers)
PHP & MYSQL: using bcrypt hash and verifying password with database
(2 answers)
Closed 5 years ago.
i'm trying to make the password_verify match the crypt password in the database, but i'm having a problem, it seems it doesn't match.
I already search for this and i've found that i need to use VARCHAR with a maximum length of 255 and still doesn't work.
Here is the code:
if( isset($_POST['bG9n']) && "bG9naW4") {
$email = $_POST['email'];
$pass= $_POST['pass'];
if($pass) {
$crypt = password_hash($pass,PASSWORD_BCRYPT);
$decrypt = password_verify($pass,$crypt);
}
if(password_verify($pass,$crypt)) {
echo "Sucess"; // It does echo Sucess
}
if (!empty($email) && !empty($pass) && filter_var($email,FILTER_VALIDATE_EMAIL) && password_verify($pass,$crypt)) {
$sql = "SELECT email, pass FROM clientes WHERE email ='$email' AND pass = '$decrypt' ";
$query = $DB_con->prepare($sql);
$query->execute();
$count = $query->rowCount();
if($count == 1){
$_SESSION['email'] = $email;
$_SESSION['pass'] = $decrypt;
header("Location: home.php");
}
else {
echo "<BR>Error";
}
}
Probably is an easy fix but i can't seem to find what's wrong.
Thanks everyone in advance.
It's a normal behaviour. Hash with bcrypt is not deterministic, it differs from launch to launch, so you can't query it.
You have to check if it matches not via mysql but via php.
So, first get it from database, then $isVerified = password_verify($pass, $hashFromDB);
Related
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
How can I get useful error messages in PHP?
(41 answers)
Closed 3 years ago.
UPDATE: I just want to update to share how I finally solved the issue I was having with the password_hash function in case others run into the same problem. I did not have the size of my password table long enough to accommodate the size of the hashed password, which worked fine for MD5. After changing the password table to 255 characters, these functions worked how they should.
I am adding users to my database and trying to use password_hash with the password they submit. Once added, users need to be able to log in. I am trying to verify the password with verify_password but it keeps coming back false.
I have been able to add users with password_hash but unable to log in with added users using the password_verify method. Strangely, if I add a user with MD5 within phpmyadmin, I can log them in no problem using md5($password). If I add users with md5 through my code, even if the passwords match, I am unable to log them in with this method.
I have been searching and searching and can't seem to figure out what I am doing wrong.
This was meant as a test to see if I can log in users. I know MD5 is not a great way. If I manually add a user and use the MD5 method in phpmyadmin, this code works:
if(md5($password) === $hashed) {
// log in user code
}
When adding the password, I am encrypting it like this:
$password = md5($_POST['password']);
Then I add it to an array and insert it into the database. Once again, this is just a test.
When I try using the password_hash function, which is what I would like to do, password_verify does not work. This is what I am trying to do.
INSERT FUNCTION:
function insertAgent($conn) {
$firstname = testdata($_POST['firstname']);
$middlename = testdata($_POST['middlename']);
$lastname = testdata($_POST['lastname']);
$phone = testdata($_POST['phone']);
$email = testdata($_POST['email']);
$position = testdata($_POST['position']);
$agency = testdata($_POST['agency']);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$agentArray[] = array(
'AgentId' => '',
'AgtFirstName' => $firstname,
'AgtMiddleInitial' => $middlename,
'AgtLastName' => $lastname,
'AgtBusPhone' => $phone,
'AgtEmail' => $email,
'AgtPosition' => $position,
'AgencyId' => $agency,
'password' => $password
);
foreach ($agentArray as $array) {
$query = "INSERT INTO agents";
$result = $conn->query($query);
$query .= " (`".implode("`, `", array_keys($agentArray[0]))."`) VALUES";
foreach ($agentArray as $array) {
$query .= " ('".implode("', '", $array)."'),";
}
$query = substr($query,0,-1); // remove last comma
$result = mysqli_query($conn, $query) or die(mysql_error());
LOGIN:
if(!empty($_POST["login"])) {
$useremail = trim($_POST['useremail']);
$password = trim($_POST['password']);
$pass_query = mysqli_query($conn, "SELECT password FROM agents WHERE AgtEmail='$useremail'");
$pass = mysqli_fetch_assoc($pass_query);
$hashed = $pass['password'];
if(password_verify($password, $hashed)) {
$result = mysqli_query($conn, "SELECT * FROM agents WHERE AgtEmail='" . $useremail . "'");
$row = mysqli_fetch_assoc($result);
if(is_array($row)) {
$_SESSION["AgentId"] = $row['AgentId'];
}
} else {
$message = "<p class='errorForm'>Invalid Email or Password</p>";
}
}
The hashed version in the DB ($hashed) matches the md5 version from the user but it results in false unless I manually add it.
This question already has answers here:
Using PHP 5.5's password_hash and password_verify function
(4 answers)
Closed 3 years ago.
I am trying to process a password as md5 into the database, this is the concerned code:
include_once("config.php");
session_start();
if(isset($_POST['signup'])){
$name = $_POST['name'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$insert = $pdo->prepare("INSERT INTO users (name,email,pass)
values(:name,:email,:pass) ");
$insert->bindParam(':name',$name);
$insert->bindParam(':email',$email);
$insert->bindParam(':pass',$pass);
$insert->execute();
}elseif(isset($_POST['signin'])){
$email = $_POST['email'];
$pass = $_POST['pass'];
$select = $pdo->prepare("SELECT * FROM users WHERE email='$email' and pass='$pass'");
$select->setFetchMode();
$select->execute();
$data=$select->fetch();
if($data['email']!=$email and $data['pass']!=$pass) {
echo "invalid email or pass";
}
elseif($data['email']==$email and $data['pass']==$pass) {
$_SESSION['email']=$data['email'];
$_SESSION['name']=$data['name'];
header("location:profile.php");
}
}
What length in the db would be appropriate to store this hashed password?
And how do I use this:
$hashed_password = password_hash($pass, PASSWORD_DEFAULT);
var_dump($hashed_password);
and the if statement if the password was ok?
Its really quite simple once you read the manual or see an example in a tutorial. See comments in the code for details
<?php
include_once("config.php");
session_start();
if(isset($_POST['signup'])){
$name = $_POST['name'];
$email = $_POST['email'];
// at signup you hash the user provided password
$pass = password_hash($_POST['pass'], PASSWORD_DEFAULT);
$insert = $pdo->prepare("INSERT INTO users (name,email,pass)
values(:name,:email,:pass) ");
$insert->bindParam(':name',$name);
$insert->bindParam(':email',$email);
$insert->bindParam(':pass',$pass); // this stores the hashed password
$insert->execute();
}elseif(isset($_POST['signin'])){
$email = $_POST['email'];
$pass = $_POST['pass'];
// as the password on the DB is hashed you cannot use the
// plain text password in the SELECT here as it wont match
$select = $pdo->prepare("SELECT * FROM users WHERE email=:email");
// no idea what this was doing
//$select->setFetchMode();
$select->bindParam(':email',$email);
$select->execute();
$row = $select->fetch(PDO::FETCH_ASSOC);
// verify the plain text password against the
// hashed value from DB in $row['pass']
if( password_verify($pass, $row['pass']) ){
$_SESSION['email'] = $data['email'];
$_SESSION['name'] = $data['name'];
header("location:profile.php");
exit;
} else {
echo "invalid email or pass";
}
}
And as to the length of the column in the database that you need to hold this hashed value, it is documented in the manual
The following algorithms are currently supported:
PASSWORD_DEFAULT - Use the bcrypt algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).
PASSWORD_BCRYPT - Use the CRYPT_BLOWFISH algorithm to create the hash. This will produce a standard crypt() compatible hash using the "$2y$" identifier. The result will always be a 60 character string, or FALSE on failure.
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 6 years ago.
I want to check if a user already exists.
I made the following code but it is not working.
The echo in the checkUser is only to look if it jumps in the if clause.
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$checkUserID = mysql_query("SELECT *
FROM users
WHERE username = '$username'");
if (mysql_num_rows($checkUserID) >= 1) {
//echo "User id exists already.";
echo "testststst";
$user1 = mysql_fetch_array($checkUserId);
$result = flashMessage("User is already taken, please try another one");
//print_r($user); // the data returned from the query
}else if(empty($form_errors)){
...formcheck...
}
I hope somebody can help me I don't know what to do.
I suggest you tu use PDO library. For your problem the best solution is to have the username in the table as PRIMATY KEY or with a UNIQUE CONSTRAINT. This way, if you try to insert two times the same username, the query will throw an exception (or will return false depending how you set it) and it's easier to do.
I can see the following problems with your code--
You haven't made any database connection.
You should check whether the $_POST variables are available or not. That is try to use if(isset) function to check it.
Try using prepared statements as they are more secure.
first of all ur code is vulnerable to sql injections. Wrapped the form data with the function.
<?php
//function to prevent sql injections
function validateFormData($formData) {
$formData = trim( stripslashes( htmlspecialchars( strip_tags( str_replace( array( '(', ')' ), '', $formData ) ), ENT_QUOTES ) ) );
return $formData;
}
$email = validateFormData($_POST['email']);
$username = validateFormData($_POST['username']);
$password = validateFormData($_POST['password']);
$checkUserID = mysql_query("SELECT *
FROM users
WHERE username = '$username'");
if (mysql_num_rows($checkUserID) >= 1) {
//echo "User id exists already.";
echo "testststst";
while ($row = mysqli_fetch_assoc($checkUserID)){
//set some variables to save some data
$usernameD = $row['username'];
}
//compare form username with db username{
if($usernameD === $username){
echo "Username already taken";
}else{
//continue the rest...
}
}
?>
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.
This question already has answers here:
The 3 different equals
(5 answers)
Closed 7 years ago.
I'm not a php programmer, so I only know what I have looked up online about the md5 tag.
I am checking to see if passwords match in a php page. I send the password in the php url and retrieve it with this code:
$u_pswd = md5(trim(strip_tags($_REQUEST['pswd'])));
Then I run a query to get the user's password so I can check if they are the same:
$usql = "SELECT user_password FROM ft_users WHERE user_email = '".$u_mail."'";
$ures = mssql_query($usql);
$urow = mssql_fetch_array($ures);
if ($urow['user_password'] = $u_pswd) {
// passwords match
} else {
// passwords do not match
}
My problem is that it says the passwords match every time. For example, if the current password is PASSWORD and I send it a password INCORRECT, the output is:
$_pswd = 64a4e8faed1a1aa0bf8bf0fc84938d25
$urow['user_password'] = 64a4e8faed1a1aa0bf8bf0fc84938d25
Could someone help me out in solving why it is saying the passwords are the same when they are not?
Do not use "=" for comparison. "=" will assign a value and any expression "$var = $value" will be evaluated to true. Use "==" instead.
if ($urow['user_password'] == $u_pswd) { ... }
= is for assigning , in your code you are assigning $u_pswd value to $urow['user_password']
you need to compare those values are equal or not by using == to get required result
$usql = "SELECT user_password FROM ft_users WHERE user_email = '".$u_mail."'";
$ures = mssql_query($usql);
$urow = mssql_fetch_array($ures);
if ($urow['user_password'] == $u_pswd) {
}
else
{
}
Hope it helps.