password change script in PHP MySQL - php

Help please with this password change script
here's mys html code
<form method="POST" action="pass.php">
Current Password:
<input type="password" name='password'/>
New Password
<input type="password" id="password1" name="password1"/>
Retype New Password:</td>
<input type="password" id="password2" name="password2"/>
<input type="submit" value="Change Password">
</form>
here's my php script for change password. it's working fine but when i try to login the new password it is always incorrect.
$userData = $qry->fetch(PDO::FETCH_ASSOC);
$hash = hash('sha256',$userData['salt'].hash('sha256',$password));
if ($hash == $userData['password']) {
$hash1 = hash('sha256', $password1);
function createSalt()
{
$text = md5(uniqid(rand(), TRUE));
RETURN substr($text, 0, 3);
}
$salt = createSalt();
$pass = hash('sha256', $salt . $hash1);
$qry = $handler->prepare( "UPDATE login SET password = ? WHERE id = ?" );
$qry->execute(array($pass,$id));
$error = 'Password successfully changed! The system will now log you out. Please login again.';
session_destroy();
header('refresh:5; url=/../lab/login.php');
}else{
$error = 'Incorrect Password.';
}
Here's my login script for reference.
<?php
$errors = array();
if ($email&&$pass){
$qry = $handler->prepare( "SELECT `email` FROM login WHERE `email` = ?" );
$qry->bindValue( 1, $email );
$qry->execute();
$row = $qry->rowCount();
if ($row == 1){
$qry = $handler->prepare( "SELECT * FROM login WHERE email = ? AND stat = '1'" );
$qry->bindValue( 1, $email );
$qry->execute();
$row = $qry->rowCount();
if ($row == '1'){
$userData = $qry->fetch(PDO::FETCH_ASSOC);
$hash = hash('sha256',$userData['salt'].hash('sha256',$pass));
if($hash == $userData['password']){
$_SESSION['email']=$email;
header('Location:/../lab/profile.php');
}
else{
$errors = "<center>The Password/Email you Entered is incorrect. Please check your login Details and <br><a href='/../lab/login.php' style='font-size:12px;text-decoration:underline;'>Login Again</a></center> ";
}
}
else{
$errors = "Your Account is not yet activated. Please check your email.";
}
}
else{
$errors = "<center>The Password/Email you Entered is incorrect. Please check your login Details and <br><a href='/../lab/login.php' style='font-size:12px;text-decoration:underline;'>Login Again</a></center>";
}
}
else{
$errors = "Please fill in the Email and Password fields to login";
}
?>
Everything is working. It's just when I try to change password and then login the new password, the system returns incorrect password. maybe there's some problem with encrypting the new password.
Thanks

Is that the full php script?
There are many ways to debug this.
Try to echo $_POST['password1']; maybe it doesn't have a value.
did you try $hash1 = hash('sha256', $_POST['password1']);?
or maybe you forgot to hash the $pass in if ($email&&$pass)
From what I saw on your code. Listed above is the most critical reason of your problem.

Related

converting multi user login

I have a user table name USERS user_id`, `username`, `user_type`, `password and I also create a login form it's working well. But I want to create a SESSION by user_type, I mean when a user will be logged in from same login page they will be redirect to different pages with SESSION ID, like "user and admin page" . I have tried with some different ways but its not working. here is my recent code how could i use user_type any help will be appreciated ! html form
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off" />
<input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="off" />
<button type="submit" class="btn btn-default"> <i class="glyphicon glyphicon-log-in"></i> Sign in</button>
`
session_start();
if(isset($_SESSION['userId'])) {
header('location: http://localhost/stock/dashboard.php');
}
$errors = array();
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) || empty($password)) {
if($username == "") {
$errors[] = "Username is required";
}
if($password == "") {
$errors[] = "Password is required";
}
} else {
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $connect->query($sql);
if($result->num_rows == 1) {
$password = md5($password);
// exists
$mainSql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$mainResult = $connect->query($mainSql);
if($mainResult->num_rows == 1) {
$value = $mainResult->fetch_assoc();
$user_id = $value['user_id'];
$_SESSION['userId'] = $user_id;
header('location:
http://localhost/stock/dashboard.php');
} else{$errors[] = "Incorrect username/password combination";
}
} else {
$errors[] = "Username doesnot exists";
} // /else
} // /else not empty username // password
} // /if $_POST
?>`
Not a full answer but possibly enough for you to do the rest. If not, I'm happy to help more.
The code would fit into your existing code after the user login has been verified.
switch ($usergroup)
{
case "ACCOUNTS":
$rootfile = dirname(__FILE__).DIRECTORY_SEPARATOR."accounts.html.php";
break;
case "ENGINEERS":
$rootfile = dirname(__FILE__).DIRECTORY_SEPARATOR."engineers.html.php";
break;
}
if (file_exists($rootfile))
{
include $rootfile;
}
else
{
echo "<br> ROOT FILE DOES NOT EXIST <br>";
}
You would have to get the UserGroup (or UserType) in a variable before this code.
ADDED LATER
You have already stored a user id reference in the session with
$_SESSION['userId'] = $user_id;
That should only be set when the user has logged in correctly
On later pages (Eg the included file for Accounts or Engineers) you may wish to first check they are already logged in
You can do this with a line like this
$user_was = $_SESSION['userId'];
Then if $user_was = "" or does not exist - the user has not logged in

MYSQL is automatically decrypting my password upon record entry

I have a script that adds an email address and password to a table. I first search to see if the email address exists in the table. If it does, I give an error message. If it does not, I add the record.
Then, using mysqli_insert_id(), I run another query to update the record I just added, encrypting the password with md5.
But every time I run it, the record is added, but the password does not get updated with the md5 version of the password. I have echo'd the query and it shows that it should be updating the password with the encryption, but it doesn't. Any ideas?
<?php
session_start();
error_reporting(E_ALL);
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "eits_Admin", "WebSpinner1", "EITS_Sandbox");
if (!$link) {
die("Database connection error");
}
$error = '';
if (!$_POST['email']) {
$error .= "<br/>An email address is required";
}
if (!$_POST['password']) {
$error .= "<br/>A password is required";
}
if ($error != "") {
$error = "There were errors in your form - ".$error;
} else {
$query = "select id from secretdiary
where email = '".mysqli_real_escape_string($link, $_POST['email'])
."' limit 1";
// echo $query;
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is not available.";
} else {
$query = "insert into secretdiary
(email,password)
values ('" . mysqli_real_escape_string($link, $_POST['email'])
. "', '"
. mysqli_real_escape_string($link, $_POST['password']) . "')";
if (!mysqli_query($link, $query)) {
$error = "Could not sign you up at this time. Please try again later.";
} else {
$encPass = md5(md5(mysqli_insert_id($link)) . $_POST['password']);
$query = "update secretdiary
set password = '" . $encPass
. "' where id = " . mysqli_insert_id($link) . " limit 1";
echo $query;
$result = mysqli_query($link,$query);
echo "Sign up successful.";
}
}
}
}
?>
<div id="error"><? echo $error; ?></div>
<form method="post">
<input type="email" name="email" placeholder= "Your Email">
<input type="password" name="password" placeholder="Password">
<input type="checkbox" name="stayLoggedIn" value=1>
<input type="submit" name="submit" value="Sign Up!">
</form>
You've got a lot of lines of code for a relatively simple process. Personally your form error handling such as if it's empty (in this case) can be remedied by adding required at the end of each HTML form input element (This is what I'd do)
Secondly, md5 isn't safe for hashing passwords (you're hashing a password not encrypting it)
Thirdly here's a way to hash the password from the form using Bcrypt which is much better than using md5 hashing. So do whatever error checking you need to do before like counting the usernames and if row > 0 die('username exists) Example of full code at base using PDO
When checking the users login simply use password_verify() function to do so
Tidy code helps people on SO understand what your problem is and is generally nicer to read. I know you may just be looking for something that 'Does the job' But it helps you when debugging and us when you're asking for help.
I'm going to give you a way that is marginally more secure than your one.
index.php
<form method="post" id="regform" action="register.php">
<input type="text" name="username" placeholder="Enter your email Address"required/>
<input type="password" name="password" placeholder="Enter your password" required/>
<input type="submit" class="indexbttn" id="indexbttn" name="enter"value="enter"/>
</form>
connect.php
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "fyp";
try{
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
?>
register.php
<?php
session_start();
require_once ('connect.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$check (!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL));
$cnt = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($cnt);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('That username already exists!');
}
$passHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
$insrt = "INSERT INTO users (username, password) VALUES (:username, :password)";
$stmt = $pdo->prepare($insrt);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passHash);
$result = $stmt->execute();
if($result){
header( "refresh:5;url=index.php" );
echo 'You will be redirected in 5 seconds. If not, click here.';
}
}
?>
login.php
<?php
session_start();
require("connect.php");
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$rtrv = "SELECT username, password, userid FROM users WHERE username = :username";
$stmt = $pdo->prepare($rtrv);
//Bind value.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch row.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
//If $row is FALSE.
if($user === false){
//Could not find a user with that username!
die('Incorrect username');
}
else{
$validPassword = password_verify($pass, $user['password']);
if($validPassword){
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /protected.php" );
die();
} else{
die('Wrong password!');
}
}
}
?>

User Authentication using mysqli_fetch_assoc() function

i've been trying to authenticate user input using the mysqli_fetch_assoc function, though it works i.e redirects user to the home page when the username and password is correct, but it doesn't display the error message(s) when the inputs are incorrect however it displays the username error message when the username is incorrect case wise. pls how do i fix it? here is the code
$username = $password = "";
$username_err = $password_err = "";
//testing input values
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//processing username input
if (empty($_POST['username'])) {
$username_err = " *username is required!";
}else{ //if field is not empty
$username = test_input($_POST['username']);
}
//processing password input
if (empty($_POST['password'])) {
$password_err = " *password is required!";
}elseif (strlen($_POST['password']) < 8) {
$password_err = " *password must not be less than 8 characters!";
}else{ //if field is not empty
$password = md5($_POST['password']);
}
//comparing user input with stored details
$sql = "SELECT * FROM users_log WHERE Username = '$username' AND Password = '$password'";
$result = mysqli_query($dbconn, $sql);
$row = mysqli_fetch_assoc($result);
if ($row) {
if ($row['Username'] != $username ) {
$username_err = "Incorrect Username";
}elseif ($row['Password'] != $password ) {
$password_err = "Incorrect Password";
}else{
header("location:../home/homeIndex.php");
}
}
}
function test_input($input){
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
the html output
<span><?php echo "$username_err<br>"; ?></span>
<input type="text" name="username" class="form-control" placeholder="Username" size="30">
</div><br>
<?php echo "$password_err<br>"; ?></span>
<input type="password" name="password" class="form-control" placeholder="Password" size="30" >
</div><br>
if ($row) {
if ($row['Username'] != $username ) {
$username_err = "Incorrect Username";
}elseif ($row['Password'] != $password ) {
$password_err = "Incorrect Password";
}else{
header("location:../home/homeIndex.php");
}
}
data inside the $row will execute when condition is true. So use if condition like this,
if ($row) {
header("location:../home/homeIndex.php");
}else{
$username_err = "Incorrect Username Or Password";
}
Hope this will resolve your issue
You are wrapping the incorrect username conditions inside if($row) , this is not going to work as inside query , you are checking for username and password both , but incase any of these is wrong , query is going to return 0 results so that means if($row) is negative and anything inside it will not work ... try below :
if ($row) {
header("location:../home/homeIndex.php");
} else {
$error = "Incorrect Username or password";
}
Why this and $error = "incorrect username or password , it's cause you are not actually checking username and password individually to say , if username is incorrect or password is incorrect. you are checking them both together which makes if($row) not to work as you want , so you better try above one.
If Username or password are incorrect the $result must be empty. Check if !empty($result).

Having issue in my if condition in my php code

I want to do is when a user click the login button and the inputs are empty its will echo please enter email and password and if the user put email and password wrong it will echo incorrect email and password .
My problem is when i click the login button and the inputs are empty it echo both please enter email and password and incorrect email and password.
I want to echo please enter email and password if both email and password are empty only and if one of email or password is wrong it should echo incorrect email and password.
<?php
require 'encryption.php';
include_once('database.php');
$db = new Connection();
$db = $db->dbConnect();
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$email = $_POST['email'];
$pass = $_POST['password'];
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
$hash = '*';
$login = $db->prepare("SELECT user_password FROM tbl_user WHERE user_email= :email");
$login->bindParam(':email', $email, PDO::PARAM_STR);
$login->execute();
$hash = $login->fetchColumn();
if(empty($email) && empty($pass)){
echo "Please enter Email and Password";
}
if($hasher->CheckPassword($pass, $hash))
{
$st = $db->prepare("SELECT * from tbl_user WHERE user_email=? AND user_password=? AND user_active='1'");
$st->bindParam(1, $email, PDO::PARAM_STR);
$st->bindParam(2, $hash, PDO::PARAM_STR);
$st->execute();
if($st->rowCount() === 1){
echo "1";
exit;
}
}else{
echo "Incorrect Email or Password";
}
?>
Change your second if to elseif.
Basically this:
if(empty($email) && empty($pass)){
echo "Please enter Email and Password";
} else {
if ($hasher->CheckPassword($pass, $hash))
echo "works"
} else {
echo "doesn't work"
}
}

How to compare entered password in input login field with the md5 password stored in database?

UPDATE(solved): Previously I set the password length to 15 characters where it should be 32 character since the password is encrypted to md5. Now it works fine. Thanks for all the answers and suggestions.
Below is the register php code. The code works fine and able to store password in the database in md5.
<html>
<?php
error_reporting(0);
if($_POST['submit'])
{
$name = mysql_real_escape_string($_POST['name']);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$password1 = mysql_real_escape_string($_POST['password1']);
$enc_password = md5($password);
if($name && $username && $password && $password1)
{
if(strlen($name)<30)
{
if(strlen($username)<10)
{
if(strlen($password)<15 || strlen($password)>6)
{
if($password == $password1)
{
require "dbc.php";
$query = mysql_query("INSERT INTO users VALUES ('$name','$username','$enc_password')");
echo "Registration Complete! <a href='index.php'>Click here to login</a>";
}
else
{
echo "Passwords must match";
}
}
else
{
echo "Your password must be between 6 and 15 characters";
}
}
else
{
echo "Your username is too long";
}
}
else
{
echo "Your name is too long";
}
}
else
{
echo "All fields are required";
}
}
?>
<form action="register.php" method="POST">
Name: <input type="text" name="name" value="<?php echo "$name"; ?>"> Max Length:30<p>
Username: <input type="text" name="username" value="<?php echo "$username"; ?>"> Max Length:10<p>
Password: <input type="password" name="password"> Max length:15<p>
Re-Enter Password: <input type="password" name="password1"><p>
<input type="submit" name="submit" value="Register">
</form>
<input type="button" value="<< Back to Login Area" onclick="window.location='../login%20and%20registration/members.php'">
</html>
Below is the login php code.
<?php
session_start();
require "dbc.php";
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$enc_password = md5($password);
if($username&&$password)
{
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrow = mysql_num_rows($query);
if($numrow!=0)
{
while($row = mysql_fetch_assoc($query))
{
$db_username = $row['username'];
$db_password = $row['password'];
}
if($username==$db_username&&$password==$db_password)
{
//echo "Logged in <a href='members.php'>Click here to enter the members area</a>";
$_SESSION['username']=$db_username;
header("location: members.php");
}
else
{
header("location: index.php?error=Incorrect Password");
}
}
else
{
header("location: index.php?error=That user doesn't exist");
}
}
else
{
header("location: index.php?error=All fields are required");
}
?>
The problem is I kept getting the "Incorrect Password" when I try to log in. I think theres something with retrieving the password from the database. Anyone can help?
You need to use $enc_password instead of $password in line:
if($username==$db_username&&$password==$db_password)
P.S. Also if you use md5 then don't do mysql_real_escape_string(), md5 will change your string and all injects will be removed.
P.P.S. Use PDO instead of mysql_*
UPDATE
Also username must be case insensitive so better to do:
if(strcasecmp($username, $db_username)===0 && $password==$db_password)
strcasecmp
change
if($username==$db_username&&$password==$db_password)
to
if($username == $db_username && $enc_password == $db_password)
You are using $password but it should be $enc_password
you're comparing $password with $db_password while you should be comparing $enc_password with $db_password.
if($username==$db_username&&$enc_password==$db_password)
In your case you should compare like this
$password = md5($password);//change value entered of password to md5
if($username==$db_username&&$password==$db_password)

Categories