Using password_verify on existing password - php

I'm trying to check the password and username of someone before they log in to my website. The passwords are all stored in password_hash($password1, PASSWORD_BCRYPT); I'm not sure as to what I'm doing wrong. At the moment, No matter what I type in, It always says Incorrect.
<?php
require 'privstuff/dbinfo.php';
$username = $_POST["username"];
$password1 = $_POST["password1"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Connection Failed. Please send an email to owner#othertxt.com regarding this problem.";
exit();
}
if ($stmt = $mysqli->prepare("SELECT `username`, `password` FROM `accounts` WHERE username = ? AND password = ?")) {
$result = mysqli_query($mysqli,"SELECT `password` FROM `accounts` WHERE username = $username");
$stmt->bind_param("ss", $username, password_verify($password1, $result);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows) {
echo("Success");
}
else {
echo("Incorrect");
}
}
$mysqli->close();
?>
This is the register.php
<?php
require 'privstuff/dbinfo.php';
$firstname = $_POST["firstname"];
$password1 = $_POST["password1"];
$email = $_POST["email"];
$ip = $_SERVER['REMOTE_ADDR'];
$username = $_POST["username"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Connection Failed. Please send an email to owner#othertxt.com regarding this problem.";
exit();
}
if ($stmt = $mysqli->prepare("INSERT INTO `accounts`(`firstname`, `username`, `password`, `email`, `ip`) VALUES (?,?,?,?,?)")) {
$db_pw = password_hash($password1, PASSWORD_BCRYPT);
$stmt->bind_param("sssss", $firstname, $username, $db_pw, $email, $ip);
$stmt->execute();
if ($stmt->affected_rows > 0) {
echo "Account successfuly created";
}
$stmt->close();
}
$stmt->close();
$mysqli->close();
?>

I fixed the issue.. I was using password_verify incorrectly.
<?php
require 'privstuff/dbinfo.php';
$username = $_POST["username"];
$password1 = $_POST["password1"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT `password` FROM `accounts` WHERE username = ?")) {
/* Bind parameters: s - string, b - blob, i - int, etc */
$stmt -> bind_param("s", $username);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
/* Close statement */
$stmt -> close();
}
if(password_verify($password1, $result))
{
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
echo '<script type="text/javascript"> window.open("textbomber.php","_self");</script>';
}else{
echo '<script type="text/javascript"> alert("Incorrect Username/Password"); window.open("login.html","_self");</script>';
}
$mysqli->close();
?>

This problem should be solved differently. Only make a single query and get the password-hash by the given username. Then the check should be done in your code, not inside a second query:
// 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);
This function will return true or false, depending on whether the password matched the stored password-hash. You cannot compare the password-hashes directly in the SQL query, because of the random salt added to each password.

Related

I can't connect my database table to my website in order to register and sign in

My website fully functions on localhost but now that I put it on web hosting the account doesn't work, I cannot register or login. I know that it works because it previously did so there is a problem with the connection to the user table in my database. The other table with products is successfully connected. How do I fix this problem in my code?
<?php
include ('connect.php');
$conn = connect();
$email = $_POST['Email'];
$pass = $_POST['Password'];
$type = $_POST['type'];
if($type == "signup"){
$sql = $conn->prepare("SELECT * FROM user WHERE Email like ?");
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
echo "This email is already in use";
}
else{
/*Part 1*/
$sqlInsert = $conn->prepare("INSERT INTO `user` (`UID`, `Email`, `Password`, `FName`, `LName`, `Country`, `City`, `Address`) VALUES (NULL, ?, ?, '', '', '', '', '');");
$sqlInsert->bind_param('ss', $email, $pass);
$sqlInsert->execute();
echo "Success!";
}
}
else if($type == "login"){
$sql = $conn->prepare("SELECT * FROM user WHERE Email like ?");
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
if($row["Password"] == $pass){
// Log in
session_start();
$_SESSION['login_user'] = $email;
$_SESSION['account_id'] = $row["UID"];
echo "Success!";
}
else{
echo "Wrong credentials!";
}
}
}
else{
echo "Wrong credentials!";
}
}
mysqli_close($conn);
?>
I think the problem may be here
<?php
include 'config.php';
function connect() {
$conn = new mysqli(SERVER_NAME, USER, PASSWORD, DB_NAME);
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
return $conn;
}
?>
you can use this code please fill below fields
my_user: default 'root'
my_password: default ''
my_db: your database name
<?php
include 'config.php';
function connect()
{
$con = mysqli_connect("localhost", "root", "", "my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
return $con;
}
?>

Error creating login system php

I've been trying to create a php login system but I can't make it work as if I try to login with valid username and password it will say "fail". I've using this technique before and was successful but this time I can't make it work.
Code:
<?php
$username=$_POST['username'];
$password=$_POST['password'];
$conn = new PDO("mysql:host=localhost;dbname=login" ,'root','');
if (!$conn){
die("Not connected". mysqli_connect_error());
}else {
echo "Connection sucessfull";
echo "</br>";
}
$sql = "select * from details where Username=$username and Password=$password";
$stmt=$conn->prepare($sql);
$stmt->bindparam("Username",$username,PDO::PARAM_STR);
$stmt->bindparam("Password",$password,PDO::PARAM_STR);
$stmt->execute();
$num = $stmt->rowCount();
if ($num>0){
echo "You are logged in";
}else {
echo "fail";
}
Thanks
Your statement should go like this:
$stmt= $conn->prepare("SELECT * FROM `details`
WHERE `Username`=:username AND `Password`=:password");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->execute();
Note:
According to php.net PDOStatement::rowCount() returns the number of
rows affected by the last DELETE, INSERT, or UPDATE statement executed
by the corresponding PDOStatement object.
So for counting the number of rows returned by select statement, you can use fetchAll():
if (count($stmt->fetchAll()) > 0) {
echo "You are logged in";
}else {
echo "fail";
}
And for setting smart PDO connection:
try {
$db_host = '';// hostname
$db_name = '';// databasename
$db_user = '';// username
$user_pw = '';// password
$conn = new PDO('mysql:host='.$db_host.'; dbname='.$db_name, $db_user, $user_pw);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$conn->exec("SET CHARACTER SET utf8");
}catch (PDOException $err) {
echo "harmless error message if the connection fails";
$err->getMessage() . "<br/>";
file_put_contents('PDOErrors.txt',$err, FILE_APPEND);//log errors
die(); // terminate connection
}
I've formatted your code and it should work now. You cannot mix mysqli_* with PDO.
$conn = new pdo("mysql:host=localhost;dbname=login;", 'root', '');
if ($conn->connect_error) {
die("Not connected" . $conn->connect_error);
}
echo "Connection successful<br/>";
$sql= "select * from details where Username=:username and Password=:password";
$result = $connection->prepare($sql);
$result->bindParam(":username" ,$_POST['username']);
$result->bindParam(":password" ,$_POST['password']);
$result->execute();
$num=$result->fetchColumn();
if($num > 0){
header("location:index.php");
}else{
header("location:login.php");
}

PHP to mySQL check if user exists

I have a script that updates/creates user from an iOS device. Now i want to have the script also check if the user already exists in the database. I am going to restrict this to username for now, so no more than ONE unique username may exist. I have an if-statement in my PHP but i cannot get it to work - help please :).
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = 'dbname';
$db_user = 'dbuser';
$db_password = 'dbpass';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
$userexists = mysql_query("SELECT * FROM users WHERE username='$username'");
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
}
if(mysql_num_rows($userexists) != 0) {
echo '{"success":0,"error_message":"Username Exist."}';
}
else {
$stmt = $mysqli->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$password = md5($password);
$stmt->bind_param('sss', $username, $password, $email);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
}
else {
echo '{"success":0,"error_message":"Username Exist."}';
}
}
}
else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Username."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
You could SELECTthe table before trying to insert username. If it already exists (= you have a result) you dont simply insert.
Better yet, use ON DUPLICATE IGNORE or something like that.

Checking if Username and Password are correct

As my code is right now, I always get the echo "Username/Password incorrect."; whether or not the username/password match or not. My question is, What did I do wrong in the code below for the php to always echo "Username/Password incorrect"
<?php
require 'privstuff/dbinfo.php';
$password1 = $_POST["password1"];
$username = $_POST["username"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Connection Failed. Please send an email to owner#othertxt.com regarding this problem.";
exit();
}
if ($stmt = $mysqli->prepare("SELECT username, password FROM accounts WHERE username=? and password=?")) {
$db_pw = password_hash($password1, PASSWORD_BCRYPT);
$stmt->bind_param("ss", $username, $db_pw);
$stmt->execute();
if ($stmt->affected_rows > 0) {
echo "Logged in.";
}else{
echo "Username/Password incorrect.";
}
$stmt->close();
}
$stmt->close();
$mysqli->close();
?>
Update I've changed if ($stmt->affected_rows > 0) to if ($stmt->num_rows). Still doesn't work though
UPDATE 2 I've realized the issue is me using password_hash($password1, PASSWORD_BCRYPT); I didn't realize that the hash gives different strings every time. I'm not understanding on how to use password_verify
The documentation of mysqli_stmt_affected_rows() says:
This function only works with queries which update a table. In order to get the number of rows from a SELECT query, use mysqli_stmt_num_rows() instead.
You also need to call mysqli_stmt_store_results() first, to buffer the results.
$stmt->store_results();
if ($stmt->num_rows > 0) {
...
}
I figured it out. I was not supposed to use password_hash again. I didn't realize that using password_hash gave different results. I then changed it to use password_verify.
<?php
require 'privstuff/dbinfo.php';
$username = $_POST["username"];
$password1 = $_POST["password1"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT `password` FROM `accounts` WHERE username = ?")) {
/* Bind parameters: s - string, b - blob, i - int, etc */
$stmt -> bind_param("s", $username);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
/* Close statement */
$stmt -> close();
}
if(password_verify($password1, $result))
{
echo("Hello");
}else{
echo("No-Go");
}
$mysqli->close();
?>

PHP/MySQL: Check if username exists

I'm a beginner in php and I want to check if the username entered already exists.
Here is my code.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
include "connect.php";
ValidateUser();
}
function ValidateUser()
{
if (!empty($_POST['username']) AND !empty($_POST['password'])) {
$queryrow=mysqli_query("SELECT * FROM websiteusers WHERE username = '$_POST['username']'");
if ($rows=mysqli_num_rows($queryrow)=0) {
RegisterUser();
}
}
function RegisterUser() {
echo "works up to here";
}
?>
It doesn't even give me an error despite turning error reporting on.
Have you even initialized a mysqli_connect?
$Connection = mysqli_connect("host","user","pass","database");
Then pass it to a function which uses mysqli_query() by:
function foo ($DB){
mysqli_query($DB,"QUERY HERE");
// Do other stuff
return /* Whatever you wish to return here*/
}
foo($Connection);
What you are trying to achieve can be done very easily with the following code. A bigger concern is security. It is good practice to both sanitize your input every time the user has a chance to input text.
Also, using prepared query's will put yet another layer of security.
Although this isn't using your provided code directly, I believe it is good to teach good habits.
If you have any questions feel free to ask.
$username = $_POST['username']; <-- sanitize this
$message = null;
$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT username FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
$stmt->fetch();
if ($stmt->num_rows() > 0) {
RegisterUser();
} else {
$message .= 'username already exists';
}
Later on when you require more items to be queried, or more results to be bound:
$stmt = $mysqli->prepare("SELECT username,password,other1,other2 FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username); <-- the "s" means the argument is a strings, if a argument is stored as an int use "i", but one character for each argument is required.
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
$stmt->fetch();
Multiple Arguments:
$stmt = $mysqli->prepare("SELECT username,password,other1,other2 FROM websiteusers WHERE username=? AND authenticated=?");
$stmt->bind_param('si', $username,$isauthenticated); <-- second argument is a INT or BOOL
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql,$passwordsql,$other1sql,$other2sql);
$stmt->fetch();
When your expecting multiple results, and lets say you want to dump them into arrays:
$userarray = array();
$stmt = $mysqli->prepare("SELECT username FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
while($stmt->fetch()){
array_push($userarray, $usernamesql);
}
$userarray is now an array of all the results fetched from the database.
Here is the right way to do this:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if(check_user($mysqli, $_POST['username']){
registerUser();
}else{
echo 'user exist, cannot register';
}
}
function check_user($conn, $username){
$query = "SELECT * FROM websiteusers WHERE username = ?";
if ($stmt = $conn->prepare($query)) {
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->close();
}
return $stmt->num_rows === 0;
}
function registerUser() {
echo "registering user ...";
}
Read up on prepared statement

Categories