I am trying to create a login system that will load a different homepage based upon what database their information is stored in - Whether they're a customer or a business.
I have created my registration and it is okay when I am trying to check just one database and it will log them in successfully.
I am unsure where to put this bit of code for the second database though - I keep receiving errors whenever i place it somewhere, I have used a similar sort of code for the first database.
mysqli_stmt_bind_param($stmt2, "s", $ema);
mysqli_stmt_execute($stmt2);
$result2 = mysqli_stmt_get_result($stmt2);
This is the code in full.
} elseif (!empty($ema) AND !empty($pas)) {
$sql1 = "SELECT * FROM users1 WHERE email1=?;";
$sql2 = "SELECT * FROM users2 WHERE email2=?;";
$stmt1 = mysqli_stmt_init ($conn);
$stmt2 = mysqli_stmt_init ($conn1);
//Check if there was an error reading data from database
if (!mysqli_stmt_prepare($stmt1, $sql1) AND !mysqli_stmt_prepare($stmt2, $sql2)) {
header("Location: ../splash.php?error=sqlerror");
} else {
mysqli_stmt_bind_param($stmt1, "s", $ema);
mysqli_stmt_execute($stmt1);
$result1 = mysqli_stmt_get_result($stmt1);
if($row1 = mysqli_fetch_assoc($result1)) {
$pwdcheck1 = password_verify($pas, $row1['pwd1']);
if($pwdcheck1 == false) {
header("Location:../splash.php?error=wrongdetails");
exit();
//If a username and password in the business account correlate, then load the business index.
} elseif ($pwdcheck1 == true){
session_start();
$_SESSION['userlog1'] = $row1['idUsers1'];
header("Location: ../../b/index1.php?login=success");
exit();
}
} elseif ($row2 = mysqli_fetch_assoc($result2)) {
$pwdcheck2 = password_verify($pas, $row2['pwd2']);
if($pwdcheck2 == false) {
header("Location: ../splash.php?error=wrongdetails");
exit();
} elseif ($pwdcheck2 == true) {
session_start();
$_SESSION['userlog2'] = $row2['idUsers2'];
header("Location: ../../t/index2.php?login=success");
exit();
}
}
}
} else {
header("Location: ../splash.php?error=usernotfound");
}
Thanks!
The fact you should have a single users table aside, the problem is coming from the numerous conditions, every one of them being useless.
Basically if you need to get the results from two queries, then you should execute them right away, one by one. Without any intermediate conditions
$sql = "SELECT * FROM users1 WHERE email1=?;";
mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "s", $ema);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result)
if (!$row) {
$sql = "SELECT * FROM users2 WHERE email2=?;";
mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "s", $ema);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
}
Now you can check the password
if(($row && password_verify($pas, $row['pwd'])) {
// OK
} else {
// not OK
}
Related
Hello I have been encountering this bug for a long time.
So basically here is by code:
function loginUser($conn, $username, $password) {
$checkExists = checkExists($conn, $username, $username);
if ($checkExists === false) {
header("Location: ../login.php?error=wronglogininfo");
exit();
}
$passwordHashed = $checkExists['password'];
$checkPassword = password_verify($password, $passwordHashed);
if ($checkPassword === false) {
header("Location: ../login.php?error=wronglogin");
exit();
} elseif ($checkPassword === true) {
$query = "SELECT * FROM users WHERE username='$username' AND password='$checkPassword'";
$query_run = mysqli_query($conn, $query);
$usertypes = mysqli_fetch_array($query_run);
if ($usertypes['usertype'] == "admin") {
header('Location: ../login.php?admin');
} elseif ($usertypes['usertype'] == "user") {
header('Location: ../login.php?user');
}
}
}
function checkExists($conn, $username, $email) {
$sql = "SELECT * FROM users WHERE username = ? OR email = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt, "ss", $username, $email);
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($resultData)) {
return $row;
} else {
$result = false;
return $result;
}
mysqli_stmt_close($stmt);
}
And so the errors work fine.
The real problem is that whenever I login with correct credentials it sends me to a 404 page with a directory I never put. I want it to send be to the admin panel or user page. Can anyone help?
This select looks like a road to ruin: SELECT * FROM users WHERE
username='$username' AND password='$checkPassword' If $checkPassword
is the result of a password_verify(). (Also be careful about possible
SQL injection.)
I suspect this is your main issue. This would essentially translate your query to:
SELECT * FROM users WHERE username = 'tony' AND password = '1';
This will likely return an empty result set, but your very next if statement is expecting a user array populated with data.
if ($usertypes['usertype'] == "admin") {
header('Location: ../login.php?admin');
} elseif ($usertypes['usertype'] == "user") {
header('Location: ../login.php?user');
}
What happens now? You won't be redirected anywhere and the current script will continue processing. So what can you do?
If you already have the user row, via checkExists() (could this be
named better?), why do another call to the database to get the
usertype?
You already have access to your user array because you called checkExists above and verified it is not false. Just use the array directly.
I just cleaned up your code a bit and added in some comments. I did not alter your queries in any way and didn't verify they are correct.
function loginUser($conn, $username, $password) {
// Renamed this variable
// Validate it and use this variable for the remainder of the function.
$user = checkExists($conn, $username, $username);
if ($user === false) {
header("Location: ../login.php?error=wronglogininfo");
exit();
}
$passwordHashed = $user['password'];
// Renamed this variable.
$validPassword = password_verify($password, $passwordHashed);
if ($validPassword === false) {
header("Location: ../login.php?error=wronglogin");
exit();
}
// You now know you have a user and a valid password.
// No need to select them again
if ($user['usertype'] == "admin") {
header('Location: ../login.php?admin');
exit;
}
if ($user['usertype'] == "user") {
header('Location: ../login.php?user');
exit;
}
// What happens if `usertype` not matched? You still need to handle this case?
}
function checkExists($conn, $username, $email) {
$sql = "SELECT * FROM users WHERE username = ? OR email = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt, "ss", $username, $email);
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
// Cleaned up this if statement
if ($row = mysqli_fetch_assoc($resultData)) {
return $row;
}
return false;
}
I am semi-new to PHP and MySQL so I was using this tutorial video to set up the forgotten password system for their previous tutorial on a login system (https://www.youtube.com/watch?v=wUkKCMEYj9M, timestamp to the part I am working on is 1:05:46).
Everything was working fine until I got to the part where we had to create the new password and anytime I submit the new password, it receives an error essentially saying that there are no rows in the database, or at least I believe that is what the error is. (Error Message: You need to re-submit your request (1)) Below I have given my code (The file for the database connector is accurately named dbc.inc.php, I messed it up when originally naming it so I just apply the different name to my scripts) and if you see what it is, I will be very grateful. Thanks!
<?php
if(isset($_POST["reset-password-submit"])) {
$selector = $_POST["selector"];
$validator = $_POST["validator"];
$password = $_POST["pwd"];
$passwordRepeat = $_POST["pwd-repeat"];
if(empty($password) || empty($passwordRepeat)) {
header("Location: ../create-new-password.php?newpwd=empty&selector=". $selector . "&validator=" . $validator);
exit();
}
else if ($password != $passwordRepeat){
header("Location: ../create-new-password.php?newpwd=pwdnotsame&selector=". $selector . "&validator=" . $validator);
exit();
}
$currentDate = date("U");
require 'dbc.inc.php';
$sql = "SELECT * FROM pwdReset WHERE pwdResetSelector=? AND pwdResetExpires >= ?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "There was an error. (1)";
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ss", $selector, $currentDate);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if(!$row = mysqli_fetch_assoc($result)) {
echo "You need to re-submit your reset request. (1)";
exit();
}
else
{
$tokenBin = hex2bin($validator);
$tokenCheck = password_verify($tokenBin, $row["pwdResetToken"]);
if($tokenCheck == false)
{
echo "You need to re-submit your reset request. (2)";
exit();
}
else if ($tokenCheck == true)
{
$tokenEmail = $row['pwdResetEmail'];
$sql = "SELECT * FROM users WHERE emailUsers=?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "There was an error. (2)";
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $tokenEmail);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if(!$row = mysqli_fetch_assoc($result)) {
echo "There was an error. (3)";
exit();
}
else
{
$sql = "UPDATE users SET pwdUsers=? WHERE emailUsers=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "There was an error. (4)";
exit();
}
else {
$newPwdHash = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ss", $newPwdHash, $tokenEmail);
mysqli_stmt_execute($stmt);
$sql = "DELETE FROM pwdReset WHERE pwdResetEmails=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "There was an error. (5)";
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $tokenEmail);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?newpwd=passwordupdated");
}
}
}
}
}
}
}
}
else {
header("Location: ../index.php");
}
I figured out what was wrong. In the page the user would input their new password on also stores the selector and token, both of which I had misspelled value on. The script above works fine with a minor tweak to the bottom part.
The new hash part should be:
$newPwdHash = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ss", $newPwdHash, $tokenEmail);
mysqli_stmt_execute($stmt);
$sql = "DELETE FROM pwdReset WHERE pwdResetEmail=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "There was an error 5";
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $tokenEmail);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?newpwd=passwordupdated");
}
Not what it was originally above.
I'm watching a login system guide on Youtube, and recreating it. It's about done, but every time i try to login, it gives me an error:
"Incorrect Password"
I suspect this has to do with the $row that was made in an if statement. But i don't know what $row does.
I'll leave some code if someone can see the problem.
<?php
else {
$sql = "SELECT * FROM users WHERE uidUsers=? OR emailUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if ($pwdCheck == false) {
header("Location: ../index.php?error=wrongpwd");
exit();
}
elseif ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header("Location: ../index.php?login=succes");
exit();
} ?>
if ($row = mysqli_fetch_assoc($result))
This tries to fetch a row from the query result. If there is a row to fetch from the results, then that row is assigned to the $row variable and the if statement is executed. If there is not a row to fetch from the results, then the if statement returns false and is skipped.
My site looks like this after login, without any navigation bar or css.
It should have included my header2.php file, which contains my nav bar and my css should be working.
Below is my code for login.php:
<?php
ob_start();
if (!isset($_POST['submit'])) {
header("Location: /../index.php?login=error");
exit();
} else {
include_once __DIR__.'/dbh.php';
include_once __DIR__.'/../header2.php';
$uid = strip_tags($_POST['uid']);
$pwd = strip_tags($_POST['password']);
$date = date("Y-m-d H:i:s");
$sql = "UPDATE users
SET user_session = ?
WHERE user_uid = ?;
";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "ss", $date, $_SESSION['u_uid']);
//Run parameters inside database
mysqli_stmt_execute($stmt);
// include error handlers:
// Check to see if the inputs are empty
//Check to see if user has activated his or her account before logging in
$user_activate = 0;
if(empty($uid) || empty($pwd)) {
echo "<meta http-equiv='refresh' content='0;url=../signup.php?signup=empty'>";
exit();
} else {
// Check to see if user has activated his or her account
$sql = "SELECT * FROM users WHERE user_activate = ? AND user_uid= ?;";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "is", $user_activate, $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
echo "<meta http-equiv='refresh' content='0;url=/../index.php?signup=notactivated'>";
exit();
} else {
// Check to see if the username exists in the database
$sql = "SELECT * FROM users WHERE user_uid = ? OR user_email = ?";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "ss", $uid, $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
echo "<meta http-equiv='refresh' content='0;url=/../index.php?login=notsignup'>";
exit();
} else {
// Does the password match the password in the database?
// while($row = mysqli_fetch_assoc($result));
if ($row = mysqli_fetch_assoc($result)) { // insert database results into an array
// De-hasing the password
$hashedPwdCheck = password_verify($pwd, $row['user_password']);
if ($hashedPwdCheck == false) {
$login_attempts = $row['login_attempts'];
$login_attempts += 1;
$sql2 = "UPDATE users
SET login_attempts = ?
WHERE user_uid = ?;
";
if (!mysqli_stmt_prepare($stmt, $sql2)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "is", $login_attempts, $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
if ($row['login_attempts'] == 5) {
$login_attempts = 0;
$user_activate = 0;
$token = 'qqewreqreqwsdfdfdafcbvcQERFGHFGHGFHRETERTDF!##$%^^()';
$token = str_shuffle($token);
$token = substr($token, 0, 10);
$sql3 = "UPDATE users
SET user_activate = ?, user_token = ?, login_attempts = ?
WHERE user_uid = ?;
";
if (!mysqli_stmt_prepare($stmt, $sql3)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "isis", $user_activate, $token, $login_attempts, $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$company = "pianocourse101#hotmail.com";
$subject = "Account temporary deactivated due to fail login attempts";
$mailTo = $row['user_email'];
$headers = "From: ".$company;
$txt = "Dear".$row['user_first']."".$row['user_last'].", \n\nYour account has been temporary deactivated because either you or someone claiming to be you has failed to log into your account on more than 5 occasions! \n\n You can use the following information to reactivate your account: \n\n Your new token: ".$token."\n\nYou can either copy and paste the token into the relevant section or click on the following link: http://localhost/loginsystem/includes/activate.php?email=".htmlspecialchars($row['user_email'])."&activatetoken=".htmlspecialchars($token);
mail($mailTo, $subject, $txt, $headers);
}
}
echo "<meta http-equiv='refresh' content='0;url=/../index.php?login=passwordfailed'>";
exit();
}
} elseif ($hashedPwdCheck == true) {
// Log in the user here
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_first'] = $row['user_first'];
$_SESSION['u_last'] = $row['user_last'];
$_SESSION['u_email'] = $row['user_email'];
$_SESSION['u_uid'] = $row['user_uid'];
$_SESSION['u_permission'] = $row['admin'];
$_SESSION['u_moderator'] = $row['moderator'];
$_SESSION['u_session'] = $row['user_session'];
$_SESSION['freelesson'] = $row['freelesson'];
$_SESSION['datejoined'] = $row['datejoined'];
$_SESSION['premium'] = $row['premium'];
// Insert into reward points when login
// Select names from rewards
$sql2 = "SELECT * FROM rewards WHERE user_uid = ?;";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql2)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "s", $uid);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
$resultCheck2 = mysqli_num_rows($result2);
while ($row2 = mysqli_fetch_assoc($result2)) {
$_SESSION['u_reward_points'] = $row2['reward_points'];
$points = 100;
$_SESSION['u_reward_points'] += $points;
$sql = "UPDATE rewards
SET reward_points = ?
WHERE user_uid = ?;
";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "is", $_SESSION['u_reward_points'], $_SESSION['u_uid']);
//Run parameters inside database
mysqli_stmt_execute($stmt);
echo "<meta http-equiv='refresh' content='0;URL=/../header2.php?login=success' />" ;
exit();
}
}
}
}
}
}
}
}
}
}
}
}
ob_end_flush();
enter image description here
Make sure the CSS files are loaded properly if loaded from external files.
Always debug your scripts with enabled PHP Error Reporting!
The final output in the browser you can see the Source code - usually Ctrl+U, or you can debug with Developers tools - usually right click the page and do Inspect element Ctrl+Shift+I - Network tab might show you some errors, same in Console tab etc.
Both should help you to identify the problematic part of your coding.
it's seems like your css files aren't loaded.
you can check through your network tab if they do loaded.
I've created a login activity and there are two edittext ids and passwords. I have a PHP code which checks the user with their id and password. If both are correct then it transfers to the other activity, but here I want a PHP code which checks the id with their specific password. If the user enters a correct id but enters an incorrect password, then it should produce an error "pls enter correct password".
Please suggest me a correct PHP code for this.
<?php
require "r_connect.php";
if($_SERVER['REQUEST_METHOD']=='POST')
{
$rollno=$_POST['rollno'];
$password=$_POST['password'];
$sql = "SELECT * FROM registration_user WHERE rollno = '$rollno' AND password='$password'";
$result = mysqli_query($connect,$sql);
$check = mysqli_fetch_array($result);
if(isset($check))
{
echo 'Success';
}
else
{
echo 'Error';
}
}
?>
Try below code for PHP:
<?php
require "r_connect.php";
if($_SERVER['REQUEST_METHOD']=='POST')
{
$rollno = $_POST['rollno'];
$password = $_POST['password'];
$sql = "SELECT password FROM registration_user WHERE rollno = '$rollno'";
$result = mysqli_query($connect,$sql);
$check = mysqli_fetch_array($result);
if(mysqli_num_rows($check) > 0)
{
if($check["password"] == $password){
echo 'Success';
}else{
echo 'pls enter correct password';
}
}
else
{
echo 'Invalid id';
}
}
?>
You can also refer this tutorial for more information
Split your SQL statement into to, at first query WHERE rollno = '$rollno', if found go on and query WHERE rollno = '$rollno' AND password = '$password', if everything's correct go on, if first statement fails user is not found, if second query fails, the user is found but password is not matching, this is your desired case.
When writing an authentication flow you can keep following things in mind :
validate your input data well
when interacting with Select queries use prepared statements whenever possible
use sha1 and md5 combinations on the password string to store in the database and comparisons.
I have tried to implement these things in the following code, of course there's always scope for improvement
function checkRollno($conn, $rollno)
{
$stmt = mysqli_stmt_init($conn);
$prepareQuery = "SELECT count(*) FROM tablename WHERE rollno = ?";
//Prepared Statements
if( mysqli_stmt_prepare($stmt, $prepareQuery ) )
{
// Bind params
mysqli_stmt_bind_param($stmt, 'i', $rollno);//i is for integer
/* execute query */
mysqli_stmt_execute($stmt);
/* Fetch Result */
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
/* close statement */
mysqli_stmt_close($stmt);
if( count($row) < 1 )
return false;
else
return true;
}
else
return false;
}
function checkUserExists($conn, $rollno, $pass)
{
$stmt = mysqli_stmt_init($conn);
$prepareQuery = "SELECT count(*) FROM tablename WHERE rollno = ? AND password= ?";
//Compare sha1 of md5 of your password (You should not store or check against exact password strings)
$pass = sha1(md5($pass));
//Prepared Statements
if( mysqli_stmt_prepare($stmt, $prepareQuery ) )
{
// Bind params
mysqli_stmt_bind_param($stmt, 'is', $rollno, sha1(md5($pass)));// s is for strings
/* execute query */
mysqli_stmt_execute($stmt);
/* Fetch Result */
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
/* close statement */
mysqli_stmt_close($stmt);
if( count($row) < 1 )
return false;
else
return true;
}
else
return false;
}
//Main Block
if( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
if( isset($_POST['rollno']) && $_POST['rollno'] != '' )
$rollno = $_POST['rollno'];
if( isset($_POST['password']) && $_POST['password'] != '' )
$pass = $_POST['password'];
$res = checkRollno($conn, $rollno);
if( $res )//rollno exists
{
if( checkUserExists( $conn, $rollno, $pass ) )
die('authenticated');//Authenticated
else
die('denied');//Wrong password
}
else//rollno doesn't exist
{
//code to reflect wrong id does not exist
}
}
I am sure you can use better function names :)
Prepared Statements
Your code could look like this :
$sql = "SELECT * FROM registration_user WHERE rollno = '$rollno'";
$result = mysqli_query($connect,$sql);
$check = mysqli_fetch_array($result);
Then you can do checks :
if(mysqli_num_rows($check) > 0)
{
if($check['password']===$password){
//id and pass correct
}else{
// id correct , but bad password
}
}else
{
echo 'Invalid id';
}