This is my code, i want to update the password with the given new password $new_password, validate it with $new_password2 and check if the current given password matches the $old_password.
<?php
if (isset($_POST['submit'])) {
//validations
$required_fields = array("username", "old_password", "password", "password2");
validate_presences($required_fields);
$fields_with_max_lengths = array("username" => 30);
validate_max_lengths($fields_with_max_lengths);
if(empty($errors)) {
//process the form
$id = $admin["id"];
$username = mysql_prep($_POST["username"]);
$new_password = password_encrypt($_POST["password"]);
$old_password = password_encrypt($_POST["old_password"]);
$new_password2 = password_encrypt($_POST["password2"]);
The two passwords you must give must be equal to each other to change the password. All three passwords are hashed. $new_password and $new_password2 are needed to validate the new password. The $old_password must also be updated with the $new_password. It must be changed if the id equals the one in the database and if the $old_password matches the current $old_password.
if ($new_password == $new_password2) {
//update
$query = "UPDATE admins SET ";
$query .= "username = '{$username}', ";
$query .= "password = '{$new_password}', ";
$query .= "old_password = '{$new_password}', ";
$query .= "password2 = '{$new_password}' ";
$query .= "WHERE id = {$id} ";
$query .= "AND old_password = '{$old_password}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
//success
$_SESSION["message"] = "Admin updated.";
redirect_to("manage_admins.php");
} else {
//failure
$_SESSION["message"] = "Admin update failed1";
}
} else {
$_SESSION["message"] = "Admin update failed2";
}
} else {
$_SESSION["message"] = "Admin update failed3";
}
} else {
}
?>
You may have meant password_hash instead of password_encrypt. Still, this would be the wrong usage. Look into password_verify. The basic idea is that you get the current hashed password for that user from the DB and then use password_verify to check the user entry against the stored hash.
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'm trying to make a register/login system. The hashed passwords are saved into database successfully but when i try to login it says "Invalid login" which means it doesn't verify the password. Help me with this, it's my first time using password hash and verify
Signup.php
<?php
include('AdminPanel/connect.php');
$name = $_POST['txt_name'];
$email = $_POST['txt_email'];
$password = password_hash($_POST['txt_pass'], PASSWORD_DEFAULT);
$radioVal = $_POST['Gender'];
if($radioVal == "Male")
{
$radioVal = "Male";
}
else if ($radioVal == "Female")
{
$radioVal = "Female";
}
$queryget = mysqli_query($con,"SELECT Email FROM signup WHERE Email='$email'") or die ("Query didnt work");
$row = mysqli_fetch_array($queryget);
$emaildb = $row['Email'];
if($emaildb!=$email){
echo"success";
$insert = mysqli_query($con,"insert into signup (Name,Email,Password,Gender) values ('$name','$email','$password','$radioVal')");
}else{
echo"Email already exists";
}
?>
Login.php
<?php
include('AdminPanel/connect.php');
session_start();
$email = $_POST['txt_email'];
$password = $_POST['txt_pass'];
$info = mysqli_query($con,"select count(*) from signup where Email = '$email' and Password = '$password'");
$row = mysqli_fetch_array($info);
if (($row[0] > 0) && password_verify($password, $row['Password']))
{
$_SESSION['txt_email']=$email;
echo "success";
}
else
{
echo "Invalid login<br>Please re-enter your credentials";
}
?>
You're selecting count(*):
$info = mysqli_query(
$con, "select count(*) from signup where Email = '$email' and Password = '$password'"
);
But then referencing a field:
$row['Password']
You need to select (at least) the field, but leave out the condition on password because the password you get won't match what's in the database:
$info = mysqli_query(
$con, "select * from signup where Email = '$email'"
);
Also, don't do that, because SQL injection.
I have created a database with a table (UserPass) which essentially stores Usernames and Passwords.
Now in my form I want to ask a user to input his username and password and while testing this, I realized that I can input any username from the database and any password to login.
Is it possible to select in the SQL query the password that is in the same line as the username?
I tried something like:
$username = $_POST['username'];
$sql = "SELECT Password FROM UserPass WHERE Username = $username";
But the following mysqli_query failed:
$query = mysqli_query($cxn, $sql);
So here is the entire action.php script:
<?php
include "info.php";
include "god.php";
session_start();
if($_POST['god'] == $god)
{
header( "refresh:0;url=../web.html" );
}
else if(empty($_POST['god']))
{
}
else
{
echo "Can't you read: DON'T TRY!!!!!!!";
exit();
}
$cxn = mysqli_connect($host, $user, $password, $dbname) or die("Go");
//check username
$userI = $_POST["username"];
$userSql = "SELECT Username FROM UserPass ";
$result = mysqli_query($cxn, $userSql) or die("Query failed!");
while($line = mysqli_fetch_assoc($result))
{
extract($line);
foreach ($line as $key => $val)
{
if($_POST['username'] == $val)
{
//check for password
$username = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT Password FROM UserPass";
$passres = mysqli_query($cxn, $sql) or die("Request cannot be handled now.");
while ($passline = mysqli_fetch_assoc($passres))
{
extract($passline);
foreach ($passline as $k => $v)
{
if($_POST['password'] == $v)
{
header( "refresh:0;url=../web.html");
}
else
{
session_destroy();
}
}
}
}
}
}
/*
if($userI == $line['Username'])
{
//check for password
$pass = $_POST['password'];
$sql = "SELECT * FROM UserPass";
$res = mysqli_query($cxn, $sql) or die("Pass query failed");
$passline = mysqli_fetch_assoc($res);
if($pass == $passline['Password'])
{
header( "refresh:4;url=../web.html");
session_start();
echo "Login succesful, session started, session id: ";
}
}
*/
/*
if($_POST['username'] == $val)
{
//check for password
$b = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM UserPass";
$passres = mysqli_query($cxn, $sql);
$passline = mysqli_fetch_row($passres);
foreach ($passline as $k => $v )
{
if($_POST['password'] == $v)
{
header( "refresh:0;url=../web.html");
session_start();
}
}
}
*/
/*
else
{
print("Destroying Laptop...US Government...Destroying Laptop...\n");
exit();
}
*/
?>
You just need to check if there is a record that contains both username and password of the same user:
$password = mysqli_real_escape_string($password);
$username = mysqli_real_escape_string($username);
$sql = "SELECT Password FROM UserPass WHERE Username = '$username' AND Password = '$password'";
if there is 1 such result, it is OK.
BTW, you should not store passwords in plain text - instead use one-way hashing function and compare only the hashes of the passwords.
Your SQL query should contain an 'AND' like this:
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$sql = "SELECT * FROM UserPass WHERE username = '{username }' AND password = '{$password}' LIMIT 1";
$query = mysqli_query($link, $sql);
if ($query && mysqli_num_rows($query)>0) {
//user is authenticated
}
?>
By using the logical operator AND your query must match two conditions to give you an answer. That conditions should be known only by the users.
Also please do not store the password field as clear text in database. It's not safe. You should use sha1 hash. For more information about this please take a look here http://en.wikipedia.org/wiki/SHA-1
formatted code:
<?php
require_once 'connectvars.php';
if (isset($_POST['submit'])) {
//set vars
$oldpw = mysqli_real_escape_string($dbc, trim($_POST['oldpw']));
$newpw = mysqli_real_escape_string($dbc, trim($_POST['newpw']));
$retype = mysqli_real_escape_string($dbc, trim($_POST['retype']));
$query = mysqli_query($dbc, 'SELECT password from user_info WHERE password = "hash(\'SHA256\',$oldpw)" and user_id = "$SESSION[\'user_id\']"'); // this line is "not working well"
if (strlen($newpw) < 7) {
if (strlen($newpw) > 32 ) {
if (mysqli_num_row($query) == 1) {
if ($newpw == $retype) {
mysqli_query($dbc, "UPDATE user_info SET password = 'hash('SHA256',$newpw)'");
$msg = "You successfully changed your password";
}
else {
$msg = "Your old password doesn't match.";
}
}
else {
$msg = "You must enter your old password correct.";
}
}
else {
$msg = "Your password must contain 32 characters or less.";
}
}
else {
$msg = "Your new password must contain at least 7 characters.";
}
?>
I think you want to improve your sql syntax.
'SELECT password
from user_info
WHERE password = "hash(\'SHA256\',$oldpw)"
and user_id = "$SESSION[\'user_id\']"'
may be corrected to
"SELECT password
from user_info
WHERE password = '" . hash('SHA256',$oldpw) ."'
and user_id = '" . $_SESSION['user_id'] . "'"
to propperly escape the string. Try to correct your update statement the same way.
I am trying to input a check-box for terms and conditions in a form, but when I registered the form without ticking the box the registration went through , (which was not suppose to be). Please help have a look.
<?php
echo "<h2>Register</h2>";
$submit = $_POST['register'];
//form data
$fullname = mysql_real_escape_string(htmlentities(strip_tags($_POST['fullname'])));
$username = strtolower(mysql_real_escape_string(htmlentities(strip_tags($_POST['username']))));
$password = mysql_real_escape_string(htmlentities(strip_tags($_POST['password'])));
$repeatpassword = mysql_real_escape_string(htmlentities(strip_tags($_POST['repeatpassword'])));
$email = mysql_real_escape_string(htmlentities(strip_tags($_POST['email'])));
$houseno = mysql_real_escape_string(htmlentities(strip_tags($_POST['houseno'])));
$addressa = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressa'])));
$addressb = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressb'])));
$addressc = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressc'])));
$county = mysql_real_escape_string(htmlentities(strip_tags($_POST['county'])));
$state = mysql_real_escape_string(htmlentities(strip_tags($_POST['state'])));
$country = mysql_real_escape_string(htmlentities(strip_tags($_POST['country'])));
$accept = mysql_real_escape_string(htmlentities(strip_tags($_POST['accept'])));
if ($submit)
{
$namecheck = mysql_query("SELECT username FROM reusers WHERE username='$username'");
$count = mysql_num_rows($namecheck);
if($count!=0)
{
die("Username already taken!");
}
//check for registration form details
if ($fullname&&$username&&$password&&$repeatpassword&&$email&&$houseno&&$addressa&&$county&&$state&&$country)
{
if($accept!= 1)
{
if ($password==$repeatpassword)
{
//check char lenght of username and fullname
if (strlen($username)>25||strlen($fullname)>25)
{
echo "Lenght of username or fullname is too long";
}
else
{
//check password length
if(strlen($password)>25||strlen($password)<6)
{
echo"Password must be between 6 and 25 characters";
}
else
{
//check password length
$emailcheck = mysql_query("SELECT email FROM reusers WHERE email='$email'");
$ecount = mysql_num_rows($emailcheck);
if($ecount!=0)
{
echo"email already registered Please sign in into your account to continue";
}
else
{
//generate random code
$code = rand(11111111,99999999);
//send activation email
$to = $email;
$subject = "Activate your account";
$headers = "From: donotreply#reacheasy.co.uk";
$body = " Hello $fullname,\n\nUsername $username,\n\n Password $password ,\n\nYou registered `and need to activate your account. Click the link below or paste it into the URL bar of your browser\n\nhttp://reach.co.uk/activate.php?code=$code\n\nThanks!";
if (!mail($to,$subject,$body,$headers))
echo "We couldn't sign you up at this time. Please try again later.";
else
{
//register the user!
//encript password
$password = md5($password);
$repeatpassword = md5($repeatpassword);
$queryreg = mysql_query("
INSERT INTO reusers VALUES ('','$fullname','$username','$password','$email','$code','0','houseno','addressa','addressb','addressc','county','state','country')
");
die("You have been registered successfully! Please check your email ($email) to activate your account<a href='index.php'>Return to login page</a>");
}
}
}
}
}
else
echo"Your passwords do not match!";
}
else
echo"Please read and accept Terms and Conditions before registering!";
}
else
echo "Please fill in <b>all</> fields!";
}
?>
$accept = ($_POST['accept'] ? 1:0);
You must use
if($accept == 1)
because $_POST['accept'] = 1 when you check the checkbox.
Now return Please read and accept Terms and Conditions before registering! when checkbox is checked and register the user when checkbox is not checked.