Produce login error only if not correct login - php

I know this has something to do with the num_rows part but after numerous attempts I still can't figure this out. Basically no matter what I enter I am receiving the 'login failed' message. If my login is correct I receive login failed and login correct. I obviously only want the error if the username/password are incorrect. Thanks in advance for any help!
else if(!$error_msg && $_POST['login']){
//Build the SQL query to match the record that matches the password and username
$sql = "SELECT id, username, password_1 FROM members WHERE username = ? AND password_1 = ? LIMIT 1";
//Prepare our query
if($stmt = $mysqli->prepare($sql)){
//Bind the Parameters to the query
$stmt->bind_param('ss', $username, $password_1);
//Execute the query
$result = $stmt->execute();
//If the query doesn't execute
if($result === false){
echo '<p class="error">No Execution</p>';
}
//Bind the results of what the query gave us to our three variables
$stmt->bind_result($id, $username, $password_1);
if($stmt->num_rows !== 1){
echo '<p class="error">Login failed</p>';
}
while($stmt->fetch()){
echo "Hey The query matched a record and you should be signed in now";
echo $id;
echo $username;
echo $password_1;
}//End While
else{
echo $mysqli->error;
echo "No entry found";
}
$mysqli->close();
}

Give this a try, working on my server.
Some of your conditional statements are missing, but am sure you can incorporate them into it.
<?php
DEFINE ('DB_USER', 'xxx');
DEFINE ('DB_PASSWORD', 'xxx');
DEFINE ('DB_HOST', 'xxx');
DEFINE ('DB_NAME', 'xxx');
$mysqli = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("could not connect");
$username = "username"; // replace with actual
$password_1 = "password"; // replace with actual
$sql = "SELECT id, username, password_1 FROM members WHERE username = ? AND password_1 = ? LIMIT 1";
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param('ss',$username,$password_1);
/* execute query */
$stmt->execute();
/* Store the result (to get properties) */
$stmt->store_result();
/* Get the number of rows */
$num_of_rows = $stmt->num_rows;
/* Bind the result to variables */
$stmt->bind_result($id, $username, $password_1);
if($stmt->num_rows !== 1){
echo '<p class="error">Login failed</p>';
}
while ($stmt->fetch()) {
echo 'ID: '.$id.'<br>';
echo 'Name: '.$username.'<br>';
echo 'Password: '.$password_1.'<br>';
}
/* free results */
$stmt->free_result();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();

Related

password_verify having a few issues hopefully someone can help me

So im making a login for a game system that uses a JSON string to read back the files, however when I Hash the password and try login it doesn't work however when the password is unhased it works fine, I think the problem lies with the password verify part.
Im just unsure where to place it if someone could guide me in the right direction that will be amazing...
So the issue is when I send the $password example test5 it only reads as test 5 and not this $2y$10$viov5WbMukXsCAfIJUTUZetGrhKE9rXW.mAH5F7m1iYGfxyQzQwD.
This was the original Code
<?php
include("dbconnect.php");
/////// First Function To Get User Data For Login
if($_GET["stuff"]=="login"){
$mysqli = new mysqli($DB_host, $DB_user, $DB_pass, $DB_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/////// Need to Grab Username And Password
$username = $_GET["user"];
$password = $_GET["password"];
$query = "SELECT username, password, regkey, banned FROM users WHERE username='$username' and password='$password'";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($username, $password, $regkey, $banned);
while ($stmt->fetch()) {
echo "{";
echo '"result": "success",';
echo '"regkey": "' . $regkey . '",';
echo '"banned": "' . $banned . '"';
echo "}";
}
$stmt->close();
}
$mysqli->close();
}
Then I tried This
<?php
include("dbconnect.php");
/////// First Function To Get User Data For Login
if($_GET["stuff"]=="login"){
$mysqli = new mysqli($DB_host, $DB_user, $DB_pass, $DB_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/////// Need to Grab Username And Password
$username = $_GET["user"];
$password = $_GET["password"];
$GetPassword = "SELECT password FROM users WHERE username='$username'";
$data = mysqli_query($GetPassword);
if(password_verify($password, $data['password'])) {
$query = "SELECT username, password, regkey, banned FROM users WHERE username='$username' and password='$password'";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($username, $password, $regkey, $banned);
while ($stmt->fetch()) {
echo "{";
echo '"result": "success",';
echo '"regkey": "' . $regkey . '",';
echo '"banned": "' . $banned . '"';
echo "}";
}
$stmt->close();
}
} else {
// password is in-correct
}
$mysqli->close();
}
$data = mysqli_query($GetPassword);
^^^---mysqli result handle/object
if(password_verify($password, $data['password'])) {
^^^^^^^^^^^^---no such element in mysqli
You never fetched your data results, so you're comparing the entered password against a non-existent element of the $data result object/handle.
You need
$row = mysqli_fetch_assoc($data);
password_verify(..., $row['password']);
Most likely you're running with error_reporting and display_errors disabled, meaning you'd never see the "undefined index" warnings that PHP would ave been throwing everytime you ran this code. Those settings should NEVER be off on a devel/debug system.
And note that you're vulnerable to sql injection attacks, so your "security" system is anything but -it's entirely useless and trivially bypassable.
There are several issues with your code, such as:
This statement $data = mysqli_query($GetPassword) is wrong. mysqli_query() expects first argument to be your connection handler, so it should be,
$data = mysqli_query($mysqli, $GetPassword);
Look at this statement, if(password_verify($password, $data['password'])) { ...
mysqli_query(), on success, returns a result set, so you can't get the password using $data['password']. First fetch the row from the result set and then get the password, like this,
$row = mysqli_fetch_assoc($data);
if(password_verify($password, $row['password'])) { ...
Look at the following query,
$query = "SELECT username, password, regkey, banned FROM users WHERE username='$username' and password='$password'";
This query won't return any rows because of this WHERE condition, ...password='$password'. So the solution is, instead using two separate queries, use only one query to validate the password and retrieve relevant data. The solution is given down below.
Your queries are susceptible to SQL injection. Always prepare, bind and execute your queries to prevent any kind of SQL injection.
If you want to build a json string then instead of doing echo "{"; echo '"result": "success",'; ..., create an array comprising of all the relevant data and then json_encode the array.
So the solution would be like this:
// your code
$username = $_GET["user"];
$password = $_GET["password"];
// create a prepared statement
$stmt = mysqli_prepare($mysqli, "SELECT username, password, regkey, banned FROM users WHERE username=?");
// bind parameters
mysqli_stmt_bind_param($stmt, 's', $username);
// execute query
mysqli_stmt_execute($stmt);
// store result
mysqli_stmt_store_result($stmt);
// check whether the SELECT query returned any row or not
if(mysqli_stmt_num_rows($stmt)){
// bind result variables
mysqli_stmt_bind_result($stmt, $username, $hashed_password, $regkey, $banned);
// fetch value
mysqli_stmt_fetch($stmt);
if(password_verify($password, $hashed_password)){
echo json_encode(array('result' => 'success', 'regkey' => $regkey, 'banned' => $banned));
}else{
// incorrect password
}
}else{
// no results found
}
mysqli_stmt_close($stmt);
// your code

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");
}

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();
?>

mysqli prepared multiple statements search not excuting

I'm trying to transition my old Mysqli queries to mysqli prepared statements, and I don't seem able to figure out how to get this working as a mysqli prepared statements - see my code below. My original query works fine see below.
<?php
// DB Settings
define('DB_SERVER', 'localhost');
define('DB_USER', 'xxxx');
define('DB_PASSWORD', 'xxxx');
define('DB_NAME', 'xxxx');
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$name = "Smith"; //Smith is Master 6 times and once as Junior Stewart Total 7 rows in my database
$search_query = '%'.$name.'%';
//Original Query - this works fine
$sql = "SELECT Master, `Junior Steward` AS `Junior_Steward` FROM past_officers WHERE `Master` LIKE
'$search_query' OR `Junior Steward` LIKE '$search_query' ";
$stmt = mysqli_stmt_init($mysqli);
if (mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_bind_param($stmt, "s", $search_query);
mysqli_stmt_bind_result($stmt, $Master, $Junior_Steward);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$count = mysqli_stmt_num_rows($stmt);
printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));//Prints number of rows
if ($count == 0) {
echo $output = "<p>There was no search results</p>"; //asign to variable $output message "There was no search results"
}
while (mysqli_stmt_fetch($stmt)) {
echo "<p>Master: $Master Junior Steward: $Junior_Steward</p>";
}
}
/* Prepared Statements Binds two variables to a prepared statement as parameters*/
//This doesn't work
$sql = "SELECT Master, `Junior Steward` AS `Junior_Steward` FROM past_officers WHERE `Master` LIKE ? OR `Junior
Steward` LIKE ?";
$stmt = mysqli_stmt_init($mysqli);
if (mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_bind_param($stmt, "s", $search_query);
mysqli_stmt_bind_result($stmt, $Master, $Junior_Steward);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$count = mysqli_stmt_num_rows($stmt);
printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));//Prints number of rows
if ($count == 0) {
echo $output = "<p>There was no search results</p>"; //asign to variable $output message "There was no search results"
}
while (mysqli_stmt_fetch($stmt)) {
echo "<p>Master: $Master Junior Steward: $Junior_Steward</p>";
}
}
/* Prepared Statements Bind one variable to a prepared statement as parameters*/
//This works but only for one parameter
$sql = "SELECT Master FROM past_officers WHERE `Master` LIKE ? ";
$stmt = mysqli_stmt_init($mysqli);
if (mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_bind_param($stmt, "s", $search_query);
mysqli_stmt_bind_result($stmt, $Master);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$count = mysqli_stmt_num_rows($stmt);
printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));//Prints number of rows
if ($count == 0) {
echo $output = "<p>There was no search results</p>"; //asign to variable $output message "There was no search results"
}
while (mysqli_stmt_fetch($stmt)) {
echo "<p>Master: $Master </p>";
}
}
$stmt->close();
$mysqli->close()
?>
You are using both the class mysqli and the functions from mysqli. You are not actually using one of them.
Choose between one of them, or use the class or use the functions like mysqli_connect();
Here is an example of how you should execute prepared statements using the class mysqli.
$stmt = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$username = "Jordy";
$password = "MyLittleSecret";
if($query = $stmt->prepare("SELECT * FROM users WHERE username = ? AND password = ?")) {
$query->bind_param("ss", $username, $password);
$query->execute();
}
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

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