Cant verify users hashed password - mysql & php - 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;
}
?>

Related

Login user using password_verify

I'm creating a back end to my website and running into issues with the login user part.
The user registration into the database is made with the password_hash function using the code below:
UserReg.php :
<?php
require_once 'db.php';
$mysqli = new mysqli($host, $user, $password, $dbname);
if($mysqli -> connect_error) {
die($mysqli -> connect_erro);
}
$username = "userF";
$password = "somePass";
$token = password_hash("$password", PASSWORD_DEFAULT);
add_user($mysqli,$username, $token);
function add_user($mysqli,$username, $token) {
$query = $mysqli->prepare("INSERT INTO users(username, password) VALUES
(?,?)");
$query->bind_param('ss',$username, $token);
$query->execute();
$result = $query->get_result();
if(!$result) {
die($mysqli->error);
}
$query->close();
}
My login form skips to a blank page even when i insert my username and password. Doesn't even go to the login error message.
Login.php
<?php
include 'db.php';
$username = $_POST['user'];
$pwd = $_POST['password'];
$sql = "SELECT password FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$stmt->bind_result($pass);
while ($result = $stmt->num_rows()) {
if($stmt->password_verify($pwd, $result)) {
echo "Your username or password is incorrect";
} else {
header("Location: Menu.php");
}
}
What am i missing?
Appreciate your help.
I think you need to take a look at password_verify how it works.
$username = $_POST['user'];
$pwd = $_POST['password'];
$sql = "SELECT username, password FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if ($stmt->num_rows == 1) { //To check if the row exists
if ($stmt->fetch()) { //fetching the contents of the row
if (password_verify($pwd, $password)) {
$_SESSION['username'] = $username;
echo 'Success!';
exit();
} else {
echo "INVALID PASSWORD!";
}
}
} else {
echo "INVALID USERNAME";
}
$stmt->close();

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.

Verifying user banned or not PHP?

This is my login.php code. User is logged in even "status" is set to "yes". How can I verify if the user is banned and can I add more statuses like "suspend", "deactivated"?
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("DBname", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from users where password='$password' AND username='$username' AND", $connection);
$rows = mysql_num_rows($query);
if($row[‘status’]==’yes’){
header("banned.php");
} else if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
$sql = mysql_query("INSERT INTO logs (`uniqueId`, `fileAccessed`, `action`, `userIp`, `userPort`, `serverIp`, `fullPath`, `protocol`, `serverVersion`, `timestamp`) VALUES ('$username', '$filename', 'Logged In', '$usrip', '$usrport', '$servip', '$scriptpath', '$servprotocol', '$servver', '$timestamp')", $connection);
header("location: ../pages/profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
Firstly don't use mySQL anymore, it is deprecated and insecure. You should look into using mySQLi or PDO instead.
The problem you are having is because $row has no value.
You are missing:
$row = mysql_fetch_assoc($result)
So it would read like this:
$query = mysql_query("select * from users where password='$password' AND username='$username' AND", $connection);
$rows = mysql_num_rows($query);
$row = mysql_fetch_assoc($result);
if($row[‘status’]==’yes’){
header("banned.php");
}
Here it is rewritten as mySQLi, use this version instead and research the difference:
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "root", "");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
// Selecting Database
$db = mysqli_select_db($connection, "DBname");
// SQL query to fetch information of registerd users and finds user match.
$query = "select * from users where password='$password' AND username='$username'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$rows = mysql_num_rows($query);
if($row[‘status’]==’yes’){
header("banned.php");
} else if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
$query = "INSERT INTO logs (`uniqueId`, `fileAccessed`, `action`, `userIp`, `userPort`, `serverIp`, `fullPath`, `protocol`, `serverVersion`, `timestamp`) VALUES ('$username', '$filename', 'Logged In', '$usrip', '$usrport', '$servip', '$scriptpath', '$servprotocol', '$servver', '$timestamp')";
$result = mysqli_query($connection, $query);
header("location: ../pages/profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}

Requesting Username & Password In PHP Session

i tried to put username & password dynamically but
It doesnt work with stored username & password in DB and stays on same page....
really depressed.
<?php include "../db/db_connection.php";
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
if($_REQUEST['txt_username'] == $username && $_REQUEST['txt_pwd'] == $pwd){
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
header("Location:dashboard.php");
}
else{
header("Location:index.php");
}
?>`
Those lines doesn't nothing..
$_SESSION['txt_username'];
$_SESSION['txt_pwd'];
maybe:
$_SESSION['txt_username'] = $user;
$_SESSION['txt_pwd'] = ...;
?
You can try this, I am not sure if this is exactly what you are looking for...
<?php session_start();
$username = $_POST['txt_username'];
$pwd =$_POST["txt_pwd"];
if(empty($username) || $username == ""){
header("location:index.php?err_msg=1");
exit;
}
if(empty($pwd) || $pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT username,password FROM users WHERE username= '$username' and password= '$pwd'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)==1){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
header("Location:index.php"); // if it stays on the same page remove this line
?>
I restructured your code to look more clean.
Also I suggest you to avoid using mysql and start using mysqli (or PDO) to avoid SQL injection attacks.
<?php session_start();
if(isset($_SESSION['txt_username']) && !empty($_SESSION['txt_username'])) {
//If we enter here the user has already logged in
header("Location:dashboard.php");
exit;
}
if(!isset($_POST['txt_username'])) {
header("location:index.php?err_msg=1");
exit;
}
else if(!isset($_POST["txt_pwd"])) {
header("location:index.php?err_msg=2");
exit;
}
$username = $_POST['txt_username'];
$pwd = $_POST["txt_pwd"];
//We use MYSQL with prepared statements BECAUSE MYSQL IS DEPRECATED
$mysqli = new mysqli('localhost', 'my_bd_user', 'mi_bd_password', 'my_bd');
$sql = "SELECT 1 FROM users WHERE username= ? and password = ?";
$stmt = $mysql->prepare($sql);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
if(!empty($result)) {
//IF we enter here user exists with that username and password
$_SESSION['txt_username'] = $username;
header("location:dashboard.php");
exit;
}
else{
header("location:index.php?err_msg=3");
}
Try it.
I checked your code and found everything is correct .I wold like you to add connection file on this.
Like
$username = "root";
$password = "password";//your db password
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("db name",$dbhandle)
or die("Could not select Database");
Thanks
Try below code :
i have reviewed and changed your code :
<?php session_start();
mysqli_connect("locahost","username","password");
mysqli_select_db("database_name");
$username = trim($_POST['txt_username']);
$pwd = trim($_POST["txt_pwd"]);
if($username == ''){
header("location:index.php?err_msg=1");
exit;
}
if($pwd == ""){
header("location:index.php?err_msg=2");
exit;
}
$sql = "SELECT `username`,`password` FROM users WHERE `username`= '".$username."' and password= '".$pwd."'";
$result = mysqli_query($sql);
if(mysqli_num_rows($result)>0){
$_SESSION['txt_username'] = $username;
$_SESSION['txt_pwd'] = $pwd;
header("location:dashboard.php");
}
else{
header("location:index.php?err_msg=3");
}
?>

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