Checking if Username and Password are correct - php

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

Related

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

Using password_verify on existing password

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.

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

Produce login error only if not correct login

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

PHP login script issues

I have a couple of questions on my login script. It's just directing me to a blank page with no errors.
If I'm using mysqli, do I need to use ? or $username and $password in
my query?
I don't understand anything going on with $stmt -> fetch(); am I using it right?
$result=mysqli_query($stmt); : does this $result variable contain both the username and password?
If that's the case, how does mysqli_num_rows($result) work?
<?php
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$username = clean($_POST['username']);
$password = clean($_POST['password']);
/* Create a new mysqli object with database connection parameters */
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT Login_ID, Login_PW,
FROM login
WHERE Login_ID='$username' AND Login_PW ='".md5($_POST['password'])."'"))
{
/* Bind parameters
s - string, b - boolean, i - int, etc */
$stmt -> bind_param("ss", $username, $password);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($username, $password);
/* Fetch the value */
while ($stmt->fetch())
{
$result=mysqli_query($stmt);
//Check whether the query was successful or not
if($result)
{//main if
if(mysqli_num_rows($result) == 1)
{
//Login Successful
session_regenerate_id();
$login = mysqli_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $login['Login_ID'];
//$_SESSION['SESS_FIRST_NAME'] = $login['firstname'];
//$_SESSION['SESS_LAST_NAME'] = $login['lastname'];
session_write_close();
header("location: member-index.php");
exit();
}
else {
//Login failed
header("location: login-failed.php");
exit();
}
}
else
{
die("Query failed");
}
}//main if close
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
?>
I was attempting to address each of your questions but, they got so mixed that I couldn't just give you an answer for each. So i took the liberty of modifying your posted script with what i believe will make it work. Perhaps some extra tweaking is still necessary. Please review comments I added inline. Also, review the following php documentation pages for more information on using mysqli functions in its object oriented form:
http://www.php.net/manual/en/mysqli-stmt.num-rows.php
http://www.php.net/manual/en/mysqli-stmt.execute.php
http://www.php.net/manual/en/mysqli-stmt.bind-result.php
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
I haven't tested it and i might have a typo or two, but here is my attempt at improving your script. Let me know what you think:
<?php
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$username = clean($_POST['username']);
$password = clean($_POST['password']);
/* Create a new mysqli object with database connection parameters */
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Is your username the same as the login_id? If not you need to change this query's where to use the username column not the login_id. */
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("
SELECT Login_ID, firstname, lastname
FROM login
WHERE Login_ID=? AND Login_PW=?
"))
{
/* Bind parameters
s - string, b - boolean, i - int, etc */
$stmt -> bind_param("ss", $username, md5($password));
/* Execute it */
$result = $stmt -> execute();
//Check whether the query was successful or not
if ($result === false) {
die("Query failed");
}
/* Bind results to variables that will be used within the fetch() loop. */
$stmt -> bind_result($login_id, $firstname, $lastname);
/* Check the number of rows returned. */
if ($stmt->num_rows !== 1) {
//Login failed
header("location: login-failed.php");
exit();
}
/* Iterate over the results of the query. */
while ($stmt->fetch())
{
//Login Successful
session_regenerate_id();
/* We can use $login_id, $firstname and $lastname cause we binded the result to those variables above. */
$_SESSION['SESS_MEMBER_ID'] = $login_id;
//$_SESSION['SESS_FIRST_NAME'] = $firstname;
//$_SESSION['SESS_LAST_NAME'] = $lastname;
session_write_close();
header("location: member-index.php");
exit();
}//main if close
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
?>
When you're using a prepared statement, you normally shouldn't substitute variables into the statement. You put ? placeholders there, and then use $stmt->bind_param() to associate these placeholders with variables.
After using $stmt->fetch(), you can reference the variables that you bound with $stmt->bind_result to access the results of the SELECT.
You shouldn't be using mysqli_query at all if you're using a prepared statement. To answer your question about how it works, $result doesn't contain the actual data. You call something like $row = mysqli_fetch_assoc($result) to get the username and password into $row.
You should use $stmt->num_rows()
I am sorry friend i don't know much about mysqli.
But this can be easily done with mysql if you want.
By the way, for your 3rd question,
$result=mysqli_query($stmt); returns only the resource id's if there is any matching records for your search criteria. and mysqli_num_rows($result); will return how many resource id's are available for that criteria.username and password will only returned after mysqli_fetch_array($result); that will make the database to fetch the record as an array for those resource id's.
hope you understand...:))
I think, the problem is with this part of your code
while ($stmt->fetch())
{
$result=mysqli_query($stmt);
You have executed the statement, and fetched it; there is no need for you to query it again . . . . I'm not familiar with mysqli as I use PDO, but I think since you binded the result to $username, $password you can access the returned values with these binded variables.
while ($result = $stmt->fetch())
{
if($result->num_rows == 1)
{
$_SESSION['SESS_MEMBER_ID'] = $result['LOGIN_ID']
//////or $_SESSION['SESS_MEMBER_ID'] = $username
You can proceed like this, I think . . .

Categories