Excuting invalid password line even if the match in database - php

In the below code i am entering the correct username and password, but what is happening the its collecting the values from the form and when he reach to line 28 (if (password_verify($password, $row['cpass'])) {) its jumping to line 33 ($password_error = "Invalid password.";) even if the values entered is matching what in the database
<?php
session_start();
require_once 'dbconn.php'; // assume this file sets up $conn PDO object
$username = "";
$password = "";
$username_error = "";
$password_error = "";
$login_error = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
// Check clients table
$stmt = $pdo->prepare('SELECT COUNT(*) FROM clients WHERE cuid = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();
$count = $stmt->fetchColumn();
if ($count == 1) {
// Check password
$stmt = $pdo->prepare('SELECT cpass FROM clients WHERE cuid = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();
$row = $stmt->fetch();
if (password_verify($password, $row['cpass'])) {
$_SESSION['username'] = $username;
header('Location: dashboard.html');
exit;
} else {
$password_error = "Invalid password.";
}
}
// If the "Remember Me" checkbox is checked
if (isset($_POST['checkbox'])) {
setcookie('username', $username, time() + (30 * 24 * 60 * 60)); // 30 days expiration
setcookie('password', $password, time() + (30 * 24 * 60 * 60)); // 30 days expiration
}
}
?>
Is there any explanation for what is happening, I tried to delete the table in the database and re-create it and then enter the data, but the problem was not resolvedŲ²

You shouldn't apply the FILTER_SANITIZE_FULL_SPECIAL_CHARS on the password as that will rewrite certain characters (e.g. < will be replaced with <). Just retrieve the raw submitted password with $password = $_POST['password']

Related

Unable to extract password hash from database with prepared statements

EDIT: To clarify, I am unable to extract the hashed password from my database using prepared statements.
I'm trying to create a login system that uses prepared statements, password_hash and password_verify.
I have created the registering form that creates the user, with the hashed password using password_hash($_POST['password'], PASSWORD_DEFAULT);
This works properly.
However, I am now stuck on creating the login form.
I am trying to get the password hash that gets stored when a user registers but I cannot get it to work with prepared statements.
This is what I currently have.
<?php
require('db.php');
if(isset($_POST['submit'])) {
$stmt = $connect->prepare('SELECT user_name, user_password FROM `users` WHERE user_name = ?');
if($stmt) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
}
}
?>
How do I use the data that I got from the select query? And how do I use it to verify the password?
I tried:
$stmt->store_result();
$stmt->bind_result($loginUsername, $hash);
That only stored the username, but not the password hash and I have no clue why.
Verifying the password would use this?
password_verify($password, $hash);
UPDATE
<?php
require('db.php');
if(isset($_POST['submit'])) {
$stmt = $connect->prepare('SELECT user_name, user_password FROM `users` WHERE user_name = ?');
if($stmt) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
// Get query results
$result = $stmt->get_result();
// Fetch the query results in a row
while($row = $result->fetch_assoc()) {
$hash = $row['user_password'];
$username = $row['user_name'];
}
// Verify user's password $password being input and $hash being the stored hash
if(password_verify($password, $hash)) {
// Password is correct
} else {
// Password is incorrect
}
}
}
?>
Read this PHP MANUAL.Try this:
<?php
require('db.php');
if(isset($_POST['submit'])) {
$stmt = $connect->prepare('SELECT user_name, user_password FROM `users` WHERE user_name = ?');
if($stmt) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
// Get query results
$stmt->bind_result($user_name,$hash);
$stmt->store_result();
// Fetch the query results in a row
$stmt->fetch();
// Verify user's password $password being input and $hash being the stored hash
if(password_verify($password, $hash)) {
// Password is correct
} else {
// Password is incorrect
}
}
}
?>
This is how I created my login system:
$stmt = mysqli_prepare($link,"SELECT user_email,user_password,user_firstname,user_lastname,user_role,username FROM users WHERE user_email=?");
mysqli_stmt_bind_param($stmt,"s",$email);
mysqli_stmt_execute($stmt);
confirmQuery($stmt);
mysqli_stmt_bind_result($stmt,$user_email,$user_password,$user_firstname,$user_lastname,$user_role,$username);
mysqli_stmt_store_result($stmt);
mysqli_stmt_fetch($stmt);
if(mysqli_stmt_num_rows($stmt) == 0)
relocate("../index.php?auth_error=l1");
else{
if(password_verify($password,$user_password)){
$_SESSION['userid'] = $user_email;
$_SESSION['username'] = $username;
$_SESSION['firstname'] = $user_firstname;
$_SESSION['lastname'] = $user_lastname;
$_SESSION['role'] = $user_role;
if(isset($_POST['stay-logged-in']))
setcookie("userid", $email, time() + (86400 * 30), "/");
relocate("../index.php?auth_success=1");
}else
relocate("../index.php?auth_error=l2");
}
mysqli_stmt_close($stmt);

Cant verify users hashed password - mysql & php

im trying to verify the users hashed password with their input but i cant get it working, so far it idenfities if theres a user with that username but it just wont verify the password. here is my code
<?php
$serverName = "localhost"; //Variables to access the user database
$username = "root";
$password = "";
$database = "snake_database";
$errors = []; //Array of all the errors to display to the user
$conn = mysqli_connect($serverName, $username, $password, $database); //Connect to the database
if(!$conn){ //If the database failed to connect
die("Database failed to connect: " .mysqli_connect_error()); //Display an error message
}
$username = $_POST['username']; //set the username/ password varaibles
$password = $_POST['password'];
$hashPass = password_hash($password, PASSWORD_DEFAULT); //Encrypt the password
$sql = "SELECT * FROM users WHERE username = ?"; //Select all usernames and passwords
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$count = mysqli_num_rows($result); //Count how many results there are
if ($count == 1)
{
$sql = "SELECT password FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if(password_verify($password, $result )){
$count = 2;
}
}
if($count == 2) //If there is 1 account that matches
{
$stmt->close(); //Close the statment and connection
$conn->close();
session_start();
$_SESSION["LoggedUser"] = $username; //Log the user in
$_SESSION["lastPage"] = "login.php";
header("location: profile.php"); //Direct the user to their profile
}else //if there is no accounts that match
{
array_push($errors, "Username or password is incorrect");
session_start();
$_SESSION["loginErrors"] = $errors;
$_SESSION["lastPage"] = "login.php"; //Make this page the last page
header("location: index.php"); //Go to the homepage
}
?>
any help is appriciated, thanks
You are doing a lot of things you dont need to do.
A SELECT * will return all the columns so you dont need to do another SELECT for just the password.
Also you should not password_hash() the password again, when checking a password against the one already stored on the database. Use password_verify() and that will do all the checking. So you pass it the hashed_password from the database and the plain text password the user just entered on the screen, it will return true or false telling you if the password entered matched the hashed one on the database
<?php
// always do this early in the code
session_start();
$serverName = "localhost";
$username = "root";
$password = "";
$database = "snake_database";
$errors = []; //Array of all the errors to display to the user
$conn = mysqli_connect($serverName, $username, $password, $database);
if(!$conn){
die("Database failed to connect: " .mysqli_connect_error());
}
// dont hash password again
//$hashPass = password_hash($password, PASSWORD_DEFAULT);
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
if(password_verify($_POST['password'], $row['password'] )){
// ----------------^^^^^^^^^^^^^^^^^^--^^^^^^^^^^^^^^^^
// Plain text pwd hashed pwd from db
$_SESSION["LoggedUser"] = $_POST['username'];
$_SESSION["lastPage"] = "login.php";
header("location: profile.php");
// put exit after a redirect as header() does not stop execution
exit;
}
} else {
$errors[] = "Username or password is incorrect";
$_SESSION["loginErrors"] = $errors;
$_SESSION["lastPage"] = "login.php";
header("location: index.php");
exit;
}
?>

Getting a value from sql table for a certain user using sessions

How to get the value of the column 'ProfilePicture' for the current user (which is stored in a session) from a database and save it into a variable?
Here is an example of a possible structure for the query:
if($email="iahmedwael#gmail.com" show 'ProfilePicture' value for that username) //declare a variable to save the value of ProfilePicture
<?php
$posted = true;
if (isset($_REQUEST['attempt'])) {
$link = mysqli_connect("localhost", "root", "", 'new1') or die('cant connect to database');
$email = mysqli_escape_string($link, $_POST['email']);
$password = mysqli_escape_string($link, $_POST['Password']);
$query = mysqli_query($link, " SELECT *
FROM 360tery
WHERE Email='$email'
OR Username= '$email'
AND Password='$password' "
) or die(mysql_error());
$total = mysqli_num_rows($query);
if ($total > 0) {
session_start();
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
} else {
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
For security purposes, it's my recommendation that you use PDO for all your database connections and queries to prevent SQL Injection.
I have changed your code into PDO. It should also get the value from the column ProfilePicture for the current user and save it to the variable $picture
Note: you will need to enter your database, name and password for the database connection.
Login Page
<?php
session_start();
$posted = true;
if(isset($_POST['attempt'])) {
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$email = $_POST['email'];
$password = $_POST['Password'];
$stmt = $con->prepare("SELECT * FROM 360tery WHERE Email=:email OR Username=:email");
$stmt->bindParam(':email', $email);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
if(password_verify($password, $row['Password'])) {
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
}else{
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
}
?>
User Page
<?php
session_start();
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$stmt = $con->prepare("SELECT ProfilePicture FROM 360tery WHERE username=:email OR Email=:email");
$stmt->bindParam(':email', $_SESSION['email']);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
$picture = $row['ProfilePicture'];
}
?>
Please let me know if you find any errors in the code or it doesn't work as planned.

Change password script works but doesn't write correct password into database

I have this script for change password :
<?php
/*
Page/Script Created by Shawn Holderfield
*/
//Establish output variable - For displaying Error Messages
$msg = "";
//Check to see if the form has been submitted
if (mysql_real_escape_string($_POST['submit'])):
//Establish Post form variables
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$npassword = mysql_real_escape_string(md5($_POST['npassword']));
$rpassword = mysql_real_escape_string(md5($_POST['rpassword']));
//Connect to the Database Server
mysql_connect("mysql..", "", "")or die(mysql_error());
// Connect to the database
mysql_select_db("") or die(mysql_error());
// Query the database - To find which user we're working with
$sql = "SELECT * FROM members WHERE username = '$username' ";
$query = mysql_query($sql);
$numrows = mysql_num_rows($query);
//Gather database information
while ($rows = mysql_fetch_array($query)):
$username == $rows['username'];
$password == $rows['password'];
endwhile;
//Validate The Form
if (empty($username) || empty($password) || empty($npassword) || empty($rpassword)):
$msg = "All fields are required";
elseif ($numrows == 0):
$msg = "This username does not exist";
elseif ($password != $password):
$msg = "The CURRENT password you entered is incorrect.";
elseif ($npassword != $rpassword):
$msg = "Your new passwords do not match";
elseif ($npassword == $password):
$msg = "Your new password cannot match your old password";
else:
//$msg = "Your Password has been changed.";
mysql_query("UPDATE members SET password = '$npassword' WHERE username = '$username'");
endif;
endif;
?>
<html>
<head>
<title>Change Password</title>
</head>
<body>
<form method="POST" action="">
<table border="0">
<tr>
<td align="right">Username: </td>
<td><input type="TEXT" name="username" value=""/></td>
</tr>
<tr>
<td align="right">Current Password: </td>
<td><input type="password" name="password" value=""/></td>
</tr>
<tr>
<td align="right">New Password: </td>
<td><input type="password" name="npassword" value=""/></td>
</tr>
<tr>
<td align="right">Repeat New Password: </td>
<td><input type="password" name="rpassword" value=""/></td>
</tr>
<tr><td>
<input type="submit" name="submit" value="Change Password"/>
</td>
</tr>
</table>
</form>
<br>
<?php echo $msg; ?>
</body>
</html>
This actually works fine, access databse and overwrite the current password, but it does not hash the password like while registration
Registration process script:
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
$error_msg = "";
if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
// Sanitize and validate the data passed in
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$error_msg .= '<p class="error">The email address you entered is not valid</p>';
}
$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
// The hashed pwd should be 128 characters long.
// If it's not, something really odd has happened
$error_msg .= '<p class="error">Invalid password configuration.</p>';
}
// Username validity and password validity have been checked client side.
// This should should be adequate as nobody gains any advantage from
// breaking these rules.
//
$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
// check existing email
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this email address already exists
$error_msg .= '<p class="error">A user with this email address already exists.</p>';
$stmt->close();
}
$stmt->close();
} else {
$error_msg .= '<p class="error">Database error Line 39</p>';
$stmt->close();
}
// check existing username
$prep_stmt = "SELECT id FROM members WHERE username = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this username already exists
$error_msg .= '<p class="error">A user with this username already exists</p>';
$stmt->close();
}
$stmt->close();
} else {
$error_msg .= '<p class="error">Database error line 55</p>';
$stmt->close();
}
// TODO:
// We'll also have to account for the situation where the user doesn't have
// rights to do registration, by checking what type of user is attempting to
// perform the operation.
if (empty($error_msg)) {
// Create a random salt
//$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE)); // Did not work
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
// Create salted password
$password = hash('sha512', $password . $random_salt);
// Insert the new user into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: INSERT');
}
}
header('Location: ./continue.php');
}
}
?>
What can I do to fix this? I want the password that is changed to be in format like while registration. Because now, when I change password, it's hashed but not + salted so it doesnt work when logging in with new password.
EDIT:
Here is login script:
<?php
include_once 'psl-config.php';
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(true); // regenerated the session, delete the old one.
}
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password
FROM members
WHERE email = ?
LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $username, $db_password );
$stmt->fetch();
// hash the password
$passwordHash = password_hash($password, PASSWORD_BCRYPT);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$username);
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['login_string'] = hash('sha512',
$password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
function checkbrute($user_id, $mysqli) {
// Get timestamp of current time
$now = time();
// All login attempts are counted from the past 2 hours.
$valid_attempts = $now - (2 * 60 * 60);
if ($stmt = $mysqli->prepare("SELECT time
FROM login_attempts
WHERE user_id = ?
AND time > '$valid_attempts'")) {
$stmt->bind_param('i', $user_id);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
// If there have been more than 5 failed logins
if ($stmt->num_rows > 5) {
return true;
} else {
return false;
}
}
}
function login_check($mysqli) {
// Check if all session variables are set
if (isset($_SESSION['user_id'],
$_SESSION['email'],
$_SESSION['username'],
$_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
$email = $_SESSION['email'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
if ($stmt = $mysqli->prepare("SELECT password
FROM members
WHERE id = ? LIMIT 1")) {
// Bind "$user_id" to parameter.
$stmt->bind_param('i', $user_id);
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if ($stmt->num_rows == 1) {
// If the user exists get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
$login_check = hash('sha512', $password . $user_browser);
if ($login_check == $login_string) {
// Logged In!!!!
return true;
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
}
function esc_url($url) {
if ('' == $url) {
return $url;
}
$url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%#$\|*\'()\\x80-\\xff]|i', '', $url);
$strip = array('%0d', '%0a', '%0D', '%0A');
$url = (string) $url;
$count = 1;
while ($count) {
$url = str_replace($strip, '', $url, $count);
}
$url = str_replace(';//', '://', $url);
$url = htmlentities($url);
$url = str_replace('&', '&', $url);
$url = str_replace("'", ''', $url);
if ($url[0] !== '/') {
// We're only interested in relative links from $_SERVER['PHP_SELF']
return '';
} else {
return $url;
}
}
Please have a look at the password_hash() and the password_verify() function, MD5 or sha512 are not appropriate to hash passwords, because they are ways too fast and can be brute-forced too easily. The password_hash function will generate the salt on its own, you won't need an extra field in the database to store it.
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
Note: Using the password_hash function, there is no need to escape the password with mysql_real_escape_string, just use the original user entry.
Edit:
So i will try to point out some problems in your code, to be honest it looks a bit strange. I would try to start anew and use PDO or mysqli instead of the mysql functions, this would make it easier to protect against SQL-injection.
Change-password script
One problem is that you reuse the $password variable, which leads to the wrong comparison, though because you used == instead of = it does nothing:
$password = mysql_real_escape_string(md5($_POST['password']));
...
$password == $rows['password'];
...
elseif ($password != $password):
$msg = "The CURRENT password you entered is incorrect.";
I myself spend a lot of time to find descriptive variable names, this helps to prevent such mistakes.
$oldPassword = $_POST['password'];
...
$passwordHashFromDb = $rows['password'];
...
elseif (!password_verify($oldPassword, $passwordHashFromDb))
$msg = "The CURRENT password you entered is incorrect.";
Then before you store the new password in the database you calculate the hash:
$username = mysql_real_escape_string($_POST['username']);
$newPassword = $_POST['npassword'];
...
$newPasswordHash = password_hash($newPassword, PASSWORD_BCRYPT);
mysql_query("UPDATE members SET password = '$newPasswordHash' WHERE username = '$username'");
Registration-script
In your registration script there are other problems, surely you don't expect the user to enter a 128 character password?
if (strlen($password) != 128) { // looks strange to me
Instead of using a different hash algo, you should use the same as above:
// Create salted password
$passwordHash = password_hash($password, PASSWORD_BCRYPT);
// Insert the new user into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password) VALUES (?, ?, ?)")) {
$insert_stmt->bind_param('sss', $username, $email, $passwordHash);
...
Login-script
In your login script you check whether the password matches the password stored in the database.
if ($db_password == $password) {
// Password is correct!
There you should test the hash like this:
if (password_verify($password, $db_password) {
// Password is correct!
The call to the password_hash() function does not help in a login script and should be removed.
There are some more comments in the modified code. Here is how you should do it.
Get the old salt from your database
//Gather database information
while ($rows = mysql_fetch_array($query)):
$username = $rows['username']; //single equals to assign value
$password = $rows['password'];
$user_salt = $rows['salt']; // here get old salt
endwhile;
and this part to read and use the old salt
else:
//$msg = "Your Password has been changed.";
$salted_password = hash('sha512', $npassword . $user_salt);// here use old salt
mysql_query("UPDATE members SET password = '$salted_password' WHERE username = '$username'");
endif;

PHP mysqli query isnt working

when the user enters their details they click on login but its not working, my connection to the database is fine its this file that is not working, any help would be appreciated, thanks
include '../connection.php'; //used to include connection file that is 1 level higher in the directory
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$fquery = 'SELECT Username FROM login LIMIT 0, 30 ';
$squery = 'SELECT Password FROM login LIMIT 0, 30 ';
$username_query = mysqli_query($dbc, $fquery);
$password_query = mysqli_query($dbc, $squery);
$username_row = mysqli_fetch_array($username_query);
$password_row = mysqli_fetch_array($password_query);
if($username == $username_row && $password == $password_row) {
echo 'username and password correct';
}
?>
<?php
include '../connection.php'; //used to include connection file that is 1 level higher in the directory
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$query = 'SELECT Username FROM login WHERE Username = ? AND Password = ?';
/* set a default value to check against */
$valid_user = '';
/* use prepared statement */
$stmt = mysqli_stmt_init($dbc);
if (mysqli_stmt_prepare($stmt, $query)) {
/* set question marks equal to values */
mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
mysqli_stmt_execute($stmt);
/* get the valid username only if query is successful */
mysqli_stmt_bind_result($stmt, $valid_user);
mysqli_stmt_fetch($stmt);
/* close the statment */
mysqli_stmt_close($stmt);
}
/* check if default was overwritten */
if($valid_user != '') {
echo 'username and password correct';
}
?>
Try this out, should accomplish what you are trying to do.
$username_query = mysqli_query($dbc, $fquery);
$password_query = mysqli_query($dbc, $squery);
$username_row = $username_query->fetch_array(MYSQLI_ASSOC);
$password_row = $password_query->fetch_array(MYSQLI_ASSOC);
if($username == $username_row['username'] && $password == $password_row['Password']) {
echo 'username and password correct';
}
$username = mysqli_real_escape_string($dbc, $_REQUEST['username']);
$password = mysqli_real_escape_string($dbc, $_REQUEST['password']);
$query = "SELECT * FROM login WHERE Username = '$username' AND Password = '$password' LIMIT 1";
if(mysqli_num_rows($query) > 0)
echo 'username and password correct';

Categories