So I have a basic login form for my website. But I've been testing the website today and I discovered that if you register as 'Andy' you can log in as 'Andy' but also as 'andy'.
To fix this issue I tried selecting the username from the database and comparing it to the $_POST['username'] via ===. But with no avail so I removed that part from the code again.
This is my basic login code can anyone help?
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$DATABASE_HOST = 'localhost';
$DATABSE_USER = 'root';
$DATABSE_PASS = '';
$DATABSE_NAME = 'test';
$_POST['username'] = htmlspecialchars($_POST['username']);
$_POST['password'] = htmlspecialchars($_POST['password']);
$con = mysqli_connect($DATABASE_HOST, $DATABSE_USER, $DATABSE_PASS, $DATABSE_NAME);
if (mysqli_connect_errno()) {
exit('Failed to connect to database' . mysqli_connect_errno());
}
if ($stmt = $con->prepare('SELECT id, password, tokens, videos FROM accounts WHERE username = ?')) {
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password, $tokens, $videos);
$stmt->fetch();
if (password_verify($_POST['password'], $password)) {
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
$_SESSION['tokens'] = $tokens;
$_SESSION['videos'] = $videos;
header('Location: home.php');
} else {
echo 'Incorrect username or password';
}
} else {
echo 'Incorrect username or password';
}
$stmt->close();
}
Based on character set and collation, non binary string comparison is case insensitive. One way is to use BINARY to compare your input with column value or use COLLATE operator to change collation in one that will result in case sensitive search.
In your case, change your query to:
SELECT id, password, tokens, videos FROM accounts WHERE BINARY username = 'Andy'
Or use COLLATE like described in MySQL docs: https://dev.mysql.com/doc/refman/8.0/en/case-sensitivity.html
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
i have a query using PDO. password match was successful when I enter only strings or number. But when my password contains #& or anything like that it will tell that password is incorrect. Though in my database that was the right password.
session_start();
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'Data-Six';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
// If there is an error with the connection, stop the script and display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
// Could not get the data that should have been sent.
die ('Please fill both the username and password field!');
}
// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $con->prepare('SELECT `used-id`, `username`, `password` FROM `user-list` WHERE `username` = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
// Store the result so we can check if the account exists in the database.
$stmt->store_result();
}
if ($stmt->num_rows > 0) {
$stmt->bind_result($username, $password, $id);
$stmt->fetch();
// Account exists, now we verify the password.
// Note: remember to use password_hash in your registration file to store the hashed passwords.
if ($_POST['password'] === $password) {
// Verification success! User has loggedin!
// Create sessions so we know the user is logged in, they basically act like cookies but remember the data on the server.
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
echo 'Welcome ' . $_SESSION['name'] . '!';
} else {
echo 'Incorrect password!';
}
} else {
echo 'Incorrect username!';
}
$stmt->close();
?>
The order of variables in bind_result doesn't follow the order of field names in the SQL query.
That said, store_result/bind_result is outdated and inconvenient method which was replaced by get_result that gets you a conventional PHP array.
Here is the code you need:
$sql = 'SELECT `used-id`, `username`, `password` FROM `user-list` WHERE `username` = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
// if ($_POST['password'] === $password) { come onm you MUST use a hash
if ($user && password_verify($_POST['password'], $user['password']))
{
...
}
as you can see it is much more concise and convenient
I just figured out how to used the PDO statement XD! thanks team. what i did was just rearranged the query to match the Bind-result.
if ($stmt = $con->prepare('SELECT `username`, `password`, `used-id` FROM `user-list` WHERE `username` = ?')) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
}
if ($stmt->num_rows > 0) {
$stmt->bind_result($username, $password, $id);
$stmt->fetch();
if ($_POST['password'] === $password) {
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
echo 'Welcome ' . $_SESSION['name'] . '!';
echo 'Welcome ' . $_SESSION['id'] . '!';
} else {
echo 'Incorrect password!';
}
} else {
echo 'Incorrect username!';
}
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 4 years ago.
I am learning how to use prepared statements in my simple login system to make it more secure.
I have followed a few different tutorials to get it working but cant get it to work. When i enter the username and password wrong it gives me the error. When i enter the username and password correct i still get the error.
What am i doing wrong?
I am new to this so apologies for any obvious errors.
I have also looked into hashing my password as it is being stored as plain text in the database at the moment but that will be my next step after i get this working.
Here is my code:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if($SERVER['REQUESTMETHOD'] == 'POST') {
if (empty($POST['username']) || empty($POST['password'])) {
$error = "Enter Username and Password";
}
else
{
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
//connect to database
include('dbconx.php');
}
$stmt = $con->prepare("SELECT * from admin where password=? AND username=?");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($id, $username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
$_SESSION['login_user'] = $username; // Initializing Session
header("location: confirm.php"); // Redirecting To Other Page
}
else {
$error = "Username or Password is incorrect";
}
mysqli_close($con); // Closing Connection
}
?>
You have your bound parameter arguments backwards. Your query binds password then username but your bind_param() uses $username then $password.
I've never been a fan of using the number of rows returned to determine existence. Instead, you can simply use fetch(). It will return a boolean value indicating whether or not there was a result.
For example
$stmt = $con->prepare('SELECT id from admin where password = ? AND username = ?');
$stmt->bind_param('ss', $password, $username); // note the order
$stmt->execute();
$stmt->bind_result($id);
if ($stmt->fetch()) {
$_SESSION['login_user'] = $username;
$_SESSION['login_user_id'] = $id; // probably important
header("Location: confirm.php");
exit; // always exit after a "Location" header
} else {
$error = "Username or Password is incorrect";
}
mysqli_stmt::store_result should be called before mysqli_stmt::bind_result, also you would need to call mysqli_stmt::seek_data and mysqli_stmt::fetch to get the result.
Example :
<?php
$db = new Mysqli(...);
$inputUsername = $_POST['username'] ?? '';
$inputPassword = $_POST['password'] ?? '';
$statment = $db->prepare('SELECT `id`,`username`,`password` FROM `admin` WHERE `username` = ?');
$statment->bind_param('s',$inputUsername);
$statment->execute();
$statment->store_result();
$statment->bind_result($id,$username,$password);
if($statment->num_rows) {
$statment->data_seek(0);
$statment->fetch();
/**
* this is not secure
* #see http://php.net/manual/en/function.password-hash.php
*/
if($inputPassword === $password) {
echo sprintf('Welcome, %s!',$username);
} else {
echo 'Incorrect password!';
}
} else {
echo sprintf('No such user with the given username (%s)',$inputUsername);
}
$statment->close();
$db->close();
Removed bind_result and store_result for get_result and fetch_assoc. It makes getting db records more flexible and stable.
Also added exit(); after redirection so no other codes will be executed after redirect command.
Typo in:
if (empty($POST['username']) || empty($POST['password']))
^ $POST should be $_POST instead.
$error is not being checked properly if empty or not. And still goes through mysqli functions block even if there is an error. Fixed that by creating an appropriate if statement that encloses the mysqli funtions block.
Also added proper indentation to the code for readability.
New Code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
$_POST['username'] = isset( $_POST['username'] ) ? $_POST['username'] : '';
$_POST['password'] = isset( $_POST['password'] ) ? $_POST['password'] : '';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Enter Username and Password";
}
else{
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
//connect to database
include('dbconx.php');
}
if( $error == "" ) {
$stmt = $con->prepare("SELECT * from students where username=? AND password=?");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 1) {
$row = $result->fetch_assoc();
$_SESSION['login_user'] = $row['username']; // Initializing Session
header("location: confirm.php");exit(); // Redirecting To Other Page
}
else {
$error = "Username or Password is incorrect";
}
mysqli_close($con); // Closing Connection
}
echo $error;
}
?>
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;
}
?>
As I was changing my MySQLi to PDO, I encountered an error when fetching hashed strings from my users table.
This was the code I used before:
CheckPassword VERIFIES VALID USING MYSQLI
$mysqli = new mysqli("localhost","_USER_","_PASS_","_DB_");
$username = '_USERNAME_';
$pass = '_PASSWORD_';
$sql = "SELECT * FROM `users` WHERE username='$username' LIMIT 1";
$result = $mysqli->query($sql);
if($assoc = $result->fetch_assoc()){
$db_pass = $assoc['userpass'];
require 'PasswordHash.php';
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
if($hasher->CheckPassword($pass, $db_pass)) {
echo "valid"; // VERIFIES VALID
} else {
echo "invalid";
}
}
The reason why I switched to PDO was to prevent SQL Injections.
But now: CheckPassword VERIFIES INVALID USING PDO
$pdo = new PDO('mysql:dbname=_DB_;host=localhost', '_USER_', '_PASS_',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$username = '_USERNAME_';
$pass = '_PASSWORD_';
$stmt = $pdo->prepare('SELECT * FROM `users` WHERE username = :u LIMIT 1');
$stmt->bindParam(':u', $username);
$stmt->execute();
if($fetch = $stmt->fetch(PDO::FETCH_ASSOC)){
$db_pass = $fetch['userpass'];
require 'PasswordHash.php';
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
if($hasher->CheckPassword($pass, $db_pass)) {
echo "valid";
} else {
echo "invalid"; // VERIFIES INVALID
}
}
}
How is it that; MySQLi fetches the hashed string different compared to PDO? No matter what encryption I use for hashing the passwords, it CANNOT validate them as true when fetching using PDO, BUT only when fetching using MySQLi?
The reason because when you comparing the password that the user enter and the password that in the database , its different , the pass that the user enter to log in to his account is not hashed while the one in the database is , so we need a way to hash the entered pass and validate it with the already hashed pass in the database . How to do that ? here
This is an example from a code that i use in my Control panel :
<?php
// connect to your database
if(isset($_POST['btn-login']))
{
$User_name = $_POST['userlogin'];
$password_user = $_POST['pass'];
$FetchUserData = $conn->prepare("SELECT * FROM users WHERE userlogin = ?");
$FetchUserData->execute(array($User_name));
$FetchedData = $FetchUserData->fetch(PDO::FETCH_ASSOC);
if ($FetchedData)
{
$password = $FetchedData['userpassword']; // Save the fetched password inside variable
$isPasswordCorrect = password_verify($password_user, $password);
if( $password_user == $isPasswordCorrect )
{
$_SESSION['login_user']=$User_name;
header("location: home.php");
}
else
{
echo "Password is wrong":
}
}
else
{
echo "User is not exist ";
}
}
?>
This Code line is the code used to hash the enterd pass with the exist pass in the database :
$isPasswordCorrect = password_verify($password_user, $password);
Small explanation :
password_verify(parameterA,parameterB)
parameterA : The password that you want it to be validate .
parameterB : the password that you want it to be validated with .(
database that is stored in the database )
Hope this answer be helpful for you .
So I'm enabling users to create accounts with a username and password. I have managed to encrypt the password when a user creates a new account using:
$hash = password_hash($password, PASSWORD_BCRYPT);
However I'm having trouble with password_verify when logging in, could someone please help me with what I have? I know it's something like this:
password_verify($password, $hash)
But I don't know how to structure it or where to add it in the code. Thanks in advance. This is what I have:
<?php
if (isset($_GET["username"]) && isset($_GET["password"]) ){
$username = $_GET["username"];
$password = $_GET["password"];
$result = login( $username, $password);
echo $result;
}
function makeSqlConnection()
{
$DB_HostName = "";
$DB_Name = "";
$DB_User = "";
$DB_Pass = "";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
return $con;
}
function disconnectSqlConnection($con)
{
mysql_close($con);
}
function login($username, $password)
{
$con = makeSqlConnection();
$sql = "select * from login where username = '$username' and password = '$password';";
$res = mysql_query($sql,$con) or die(mysql_error());
$res1 = mysql_num_rows($res);
disconnectSqlConnection($con);
if ($res1 != 0) {
return 1;
}else{
return 0;
}// end else
}// end of Function
?>
The general practice is as follows:
Fetch password hash from the database where the username = the inputted username.
If rows are found, then there's a user
Now you compare the inputted password against the hash stored in the database.
I'll outline the above flow in some pseudo code for you here:
$query = SELECT password FROM users WHERE username = '$username'
$data = FETCH_THE_DATA($query);
if(password_verify($USER_INPUTTED_PASSWORD, $data['password'])) {
// password is correct
} else {
// password is in-correct
}
Notes
Stop using mysql_* functions. The library is deprecated as it's unreliable and will be removed in future releases of PHP.
You're better off using PDO or MySQLi Prepared Statements
You should always read the manual - password_verify(), it states clearly that you compare the "user inputted password" against the hashed version which is stored in your database.
Since I'm feeling good and sleepy today, I'll write a bunch of codes.
This is an example how to use PDO with prepared statement. You will have to tweak it according to your needs and you have to check if the post/get not empty as well.
I prefer to use POST request for login so this example will use POST request..
This is my user class. Which use placeholders and binding instead of passing the parameters into the query directly. This will give some protections against SQL injection attack.
class User{
private $dbh;
function __construct(){
$this->dbh = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME.';charset=utf8mb4', DB_USER, DB_PASSWORD) or die('db connect error');
}
function create($username, $password){
$status = false;
try{
$stmt = "INSERT INTO login (username, password)
VALUES (?, ?)";
$qry = $this->dbh->prepare($stmt);
$qry->bindParam(1, $username);
$qry->bindParam(2, $password);
$status = $qry->execute();
}catch(PDOException $e){
$e->getMessage();
}
$qry->closeCursor();
return $status;
}
public function getPassword($username){
$status = false;
try{
$stmt = "SELECT * FROM login WHERE username = ? LIMIT 1";
$qry = $this->dbh->prepare($stmt);
$qry->bindParam(1, $username);
$qry->execute();
$status = $qry->fetch(PDO::FETCH_ASSOC);
}catch(PDOException $e){
$e->getMessage();
}
$qry->closeCursor();
return $status;
}
}
This is how to create the user. Note that I don't check if the username already exist. You can either implement it yourself or use unique index on username column provided that the collation is case insensitive.
I have also increased the cost from the default that is 10 and I defined PASSWORD_DEFAULT to be used because I want the PHP engine to always use the strongest available algorithm (currently bcrypt).
function hashPassword($password){
$password = password_hash($password, PASSWORD_DEFAULT,array('cost' => 16));
return $password;
}
$user = new User;
$_POST['password'] = hashPassword($_POST['password']);
if(!$user->create(trim($_POST['username']),$_POST['password'])){
echo 'Failed creating user';
}else{
echo 'User created';
}
This is how to verify the password.
$user = new User;
$getPassword = $user->getPassword(trim($_POST['username']));
if(!$getPassword){
echo 'Error fetching user';
}else{
if(!password_verify($_POST['password'], $getPassword['password'])){
echo 'Login failed';
}else{
echo 'Login successful';
}
}