PHP returns multiple strings - php

I'm trying to build a login page for my forums using Apache and MySQL XAMPP Databases, But it returns the echo string multiple times, I know it goes through all of the rows in the database checking if it's true or not it returns it as "Invalid Username or Password!" until it Finds the correct login information then returns "Welcome" Might be.
while($rows = mysql_fetch_row($result)) {
//echo $rows;
if($name==$rows[1]) {
if($pass==$rows[2]) {
echo "Welcome!";
}
}
else if ($name!==$rows[1]) {
echo "Invalid Username or Password!";
if($pass!==$rows[2]) {
echo "Invalid Username or Password!";
}
}
$row = $row + 1;
}
Here is my Output:
Invalid Username or Password!Invalid Username or Password!Invalid
Username or Password!Invalid Username or Password!Welcome!
How is it done so it returns just the one that is incorrect and correct strings?.

I'm going about this from a different perspective. First of all the mysql_* extension is deprecated in as of PHP 5.5.0 and it's use is discouraged.
The next thing is I think you're going the wrong way about this. Why loop through the entire table for credentials when you can just check if there is a record with that username and that password? This is highly inefficient.
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? && password = ?");
$stmt->bind_param("ss", $name, $pass);
$stmt->execute();
$stmt->store_result();
$stmt->close();
// we found a record so the username and password match
if ($stmt->num_rows > 0) {
echo 'Welcome!';
// no records so either the username or password doesn't match
} else {
echo 'Invalid Username or Password!';
}

Keep your code outside loop for return one row
$rows = mysql_fetch_row($result);
//echo $rows;
if($name==$rows[1]) {
if($pass==$rows[2]) {
echo "Welcome!";
}
}
else if ($name!==$rows[1]) {
echo "Invalid Username or Password!";
if($pass!==$rows[2]) {
echo "Invalid Username or Password!";
}
}

use simple code
$sql=mysql_query("select * from `admin_details` where admin_email='$email' and admin_pass='$pass'");
if (mysql_num_rows($sql) > 0) {
echo "Welcome!";
} else {
echo "Invalid Username or Password!";
}

Related

Why PHP authentication works incorrect?

I am newbie in PHP.
I have simple authentication script. It works incorrect: user "test" (100% existing in table in DB) can not pass auth (error text - "User is not found!").
Use PHP7, MySQL, connection method is PDO.
Need some help please.
$data = $_POST;
// check if button is pressed
if (isset($data['enter-auth'])) {
// check fileds
$errors = array();
if (trim($data['login_auth']) == '' ) {
$errors[] = 'Enter login';
}
if (($data['password_auth']) == '' ) {
$errors[] = 'Enter password';
}
// If all fields are filled, save user's data in vars
$login = $data['login_auth'];
$password = password_hash($data['password_auth'], PASSWORD_DEFAULT);
// ... and look in table
try {
if (empty($errors)) {
// Check if login and password exists in table
$stmt = $pdo->prepare("SELECT count(*) FROM users WHERE login=? AND password=?");
$stmt->execute([$login, $password]);
$count = $stmt->fetchColumn();
// If login and pwd found in table counter will be > 0, so ...
if ($count > 0) {
// ... then we can check if password is correct
if (password_verify($data['password_auth'], $password)) {
// if entered and stored passwords match, user is welcome
$_SESSION['auth_name'] = $data['login_auth'];
echo '<div style="color: green;">Welcome, '.$_SESSION['auth_name'].';
echo 'Exit';
header('Location: /a/index.php');
} else {
$errors[] = 'Password is incorrect';
echo '<p id="message">Wrong password!</p>';
}
} else {
$errors[] = 'User not found';
echo '<p id="message">User is not found!</p>';
}
} else {
echo '<div style="color: red;">'.array_shift($errors).'</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
// close condition check if button is pressed
}
Notes:
I tryed debugging this script using var_dump.
If I use fetchAll() when searching in table, any entered ldin is accepted (even if there is no such user).
Used try/catch construction with debug aim, I've heard that in production it is deprecated because of security reason.
Found mistakes, rewrote the code according to https://phpdelusions.net/pdo_examples/password_hash
So, correct fragment is:
try {
if (empty($errors)) {
$stmt = $pdo->prepare("SELECT login, password FROM users WHERE login=?");
$stmt->execute([$login]);
$user = $stmt->fetch();
if ($user && password_verify($data['password_auth'], $user['password'])) {
$_SESSION['auth_name'] = $data['login_auth'];
echo '<div style="color: green;">Welcome, '.$_SESSION['auth_name'].';
echo 'Exit';
header('Location: /a/index.php');
} else {
$errors[] = 'Login or password error';
echo '<p id="message-auth">Login or password is incorrect!</p>';
}
} else {
echo '<div style="color: red;">'.array_shift($errors).'</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}

My MySQL query and while loop and SESSIONS aren't working PHP

In my signup up form I automatically log the user in after they submit all their data. After they submit their data to the database, I run a query to grab that data from the database and store it in session variables. The problem is that The while loop only stores the first variable which is the user ID and doesn't store the rest. What I am Doing wrong?
if ($signup) {
//user clicked the register button
if (isset($username, $em, $pass, $pass2, $fn, $ln, $sex, $bd_day, $bd_month, $bd_year)) {
//if all of these have a value
if ($pass == $pass2) {
//if the passwords match
$sql = mysqli_num_rows(mysqli_query($con, "SELECT * FROM users WHERE username = '$username'"));
//check if username is already taken
if ($sql < 1) {
//if the username hasn't been taken
$sql2 = mysqli_num_rows(mysqli_query($con, "SELECT * FROM users WHERE email = '$em'"));
//check if the email is taken
if ($sql2 < 1) {
//the email hasn't been taken
if (strlen($pass) > 5) {
//password is more than 5 characters
$pass = md5($pass);
//md5 is not secure!!! use something else later
if (strlen($username) > 4) {
//username is bigger than 4 characters
$query = mysqli_query($con, "INSERT INTO users (username, email, first_name, last_name, sex, bd_month, bd_year, bd_day, password, profile_pic, signup_date, activated, cover_photo) VALUES ('$username','$em','$fn', '$ln', '$sex', '$bd_month', '$bd_year', '$bd_day', '$pass', 'profilepic/default.png','$date)','0', 'coverphoto/defaultcover.jpg')") or die(mysqli_error($con));
//insert into db
$sql3 = mysqli_query($con, "SELECT * FROM users WHERE username = '$username' AND email = '$em'") or die(mysqli_error($con));
//select values from db for login
$num = mysqli_num_rows($sql3);
//check how many hits the query gets it should be 1
if ($sql3 == true && $num > 0) {
//check if query was a success and that there is a user with those credentials
while ($row = mysqli_fetch_assoc($sql3))
//log user in
$_SESSION['id'] = $row['id'];
echo $_SESSION['id'] . '<br>';
$_SESSION['un'] = $row['username'];
echo $_SESSION['un']. '<br>';
$_SESSION['fn'] = $row['first_name'];
echo $_SESSION['fn'] . '<br>';
$_SESSION['ln'] = $row['last_name'];
echo $_SESSION['ln'] . '<br>';
$_SESSION['em'] = $row['email'];
echo $_SESSION['em'] . '<br>';
$_SESSION['pp'] = $row['profile_pic'];
echo $_SESSION['pp'] . '<br>';
$_SESSION['signup_date'] = $row['signup_date'];
$_SESSION['active'] = $row['activated'];
setcookie('un', $username, time()+3600*60*24*7*4);
echo "You have been logged in.";
exit();
} else {
echo "An unknown error occurred";
exit();
}
} else {
//username is less than 4 characters
echo "Your username must be larger than 4 characters!";
exit();
}
} else {
//password is less than 5 characters
echo "You password must be more than 5 characters long<br />";
exit();
}
} else {
//email is already taken
echo "That email has already been taken!";
exit();
}
} else {
//username is already taken
echo "That username is already taken!";
exit();
}
} else {
//the passwords don't match
echo "You passwords don't match";
exit();
}
} else {
//user didn't submit the form
echo "Please fill in all the fields";
exit();
}
} else {
//user didn't click the register button
}
In the end it does echo You have been logged in. Also, I echoed out the values in the session variables for testing but all the return are the <br> not the actual values except for the user ID at the beginning. I don't get any errors either.
Please help me.
while ($row = mysqli_fetch_assoc($sql3))
You forgot to add { and it seems that also } at the end of the loop.
So only the first command takes place in the loop and executed.
Another thing, the "else" after the loop - to which condition is it relate?
Usually I think indents are good, but you took it too far.
Maybe, instead of nesting too many conditions and loops, find another approach.

PHP crypt validation with PDO prepared statement Error

and sorry for the [duplicate]. i spent a day, not able to find a solution. I am having a problem with crypt (validation), here is my code:
function generateHash($password, $round=10){
$salt=substr(base64_encode(openssl_random_pseudo_bytes(17)),0,22);
$salt=str_replace("+",".",$salt);
$param='$'.implode('$',array(
"2y",
str_pad($round,2,"0",STR_PAD_LEFT),
$salt
)
);
return crypt($password,$param);
}
//NOW I INSERT HASH TO DB
$input = "abc";
$hashed = generateHash($input);
$createAccount=$db->prepare("INSERT INTO account ....
':secret' => $hashed;
.....)); // Until here, no problem, $hashed can be inserted correctely into my db (password, Varchar (64)
Now after registration, user likes to login, here is the problem. First, i'm checking, to see, if i did well the function
$input = "abc";
$forCheck = "abc";
$hashedHash = generateHash($input);
if (crypt($forCheck, $hashedHash) == $hashedHash) {
echo "MATCH";
}else {
echo "NOT MATCH";
}
// OUTPUT: "MATCH"
The problem is here:
$check=$db->prepare("SELECT id, password FROM account WHERE email = :email ");
$check->execute(array(
':email' => $user
)
);
if ($check->rowCount() <= 0) {
echo "You are not registered";
}else {
$sRow=$check->fetchAll(PDO::FETCH_ASSOC);
foreach ($sRow as $row) {
$hashedHash = generateHash($row['password']);
if (crypt($input, $hashedHash) == $hashedHash) {
echo "Passwords Matched";
}else {
echo "Passwords did not match";
}
}
}
// OUTPUT: "Passwords did not match"
Any help please ?
The problem is here...
$hashedHash = generateHash($row['password']);
You aren't storing a plain text password so why would you pass the hash through generateHash again? Should simply be
if (crypt($input, $row['password']) == $row['password'])
I'd also take this opportunity to clean up your query logic. For one thing, PDOStatement::rowCount should not be relied upon.
$check = $db->prepare('SELECT id, password FROM account WHERE email = :email LIMIT 1');
$check->execute([':email' => $user]);
if ($row = $check->fetch(PDO::FETCH_ASSOC)) {
if (crypt($input, $row['password']) == $row['password']) {
echo 'Passwords Matched';
} else {
echo 'Password did not match';
}
} else {
echo 'You are not registered';
}

When Click to login Providing error

in this if in my database all the user details are held and i want to login then this code can generate error... my main work is to when i have data in databse then i can login with exist data it provide error and not logged and if filled wrong data then page not providing error, it redirect ..
ineed that when i fill correct then go to successfull page if filled wrong then provide error
<?php
include('./includes/config.php');
if(isset($_POST['submit_form']))
{
$email1=$_POST["email"];
$password1=$_POST["password"];
$query="select * from login";
$result = mysql_query($query);
$num=mysql_num_rows($result);
if($num>0)
{
while($row=mysql_fetch_array($result)){
$email2=$_POST["email"];
$password2=$_POST["password"];
}
if ($email1==$email2 && $password1==$password2) {
echo "You are in";
}
else {
echo "Sorry $email. Incorrect password!";
}
}
What are you doing check on login condition because you are comparing to every user. Also use mysqli_ instead of mysql
if(isset($_POST['submit_form']))
{
$email1=$_POST["email"];
$password1=$_POST["password"];
$query="select * from login where email='$email1' AND password='$password1";
$result = mysql_query($query);
$num=mysql_num_rows($result);
if($num>0)
{
echo "You are in";
}
else
{
echo "Sorry $email. Incorrect password!";
}
}
You're comparing the entered username and password against every user in the database. So for every other user, you print the error message. And even when you find the matching user, you don't stop, you keep going.
You should just look for the user with the username and password that was entered:
$email1 = mysql_real_escape_string($_POST['email']);
$password1 = mysql_real_escape_string($_POST['password']);
$query = "select * from login where email = '$email1' and password = '$password1'";
$result = mysql_query($query) or die (mysql_error());
$num = mysql_num_rows($result);
if ($num == 0) {
echo "Incorrect email or password.";
} else {
echo "You are in";
}

Log in returns blank for incorrect password?

I have been using a tutorial for a registration and log in page. Everything is perfect except when a user inputs an incorrect password.
If no password is entered then the stated error is displayed fine.
If the correct password is entered it logs them in.
If the incorrect password is entered it goes to a blank page?!
I want an incorrect password to display a message just like when the wrong username is entered. I've included my entire login.php code:
include('db.php');
if(!isset($_POST['login'])) {
include('form.php');
} else {
if(isset($_POST['user'])&&$_POST['user']==""||!isset($_POST['user'])) {
$error[] = "Username Field can't be left blank";
$usererror = "1";
}
if(!isset($usererror)) {
$user = mysql_real_escape_string($_POST['user']);
$sql = "SELECT * FROM users WHERE user = '$user'";
if(mysql_num_rows(mysql_query($sql))=="0") {
$error[] = "Can't find a user with this username";
}
}
if(isset($_POST['pass'])&&$_POST['pass']==""||!isset($_POST['pass'])) {
$error[] = "password Field can't be left blank";
}
if(isset($error)) {
if(is_array($error)) {
echo "<div class=\"error\"><span>please check the errors and refill the form<span><br/>";
foreach ($error as $ers) {
echo "<span>".$ers."</span><br/>";
}
echo "</div>";
include('form.php');
}
}
if(!isset($error)) {
$suser=mysql_real_escape_string($_POST['user']);
$spass=md5($_POST['pass']);//for secure passwords
$find = "SELECT * FROM users WHERE user = '$suser' AND password = '$spass'";
if(mysql_num_rows(mysql_query($find))=="1"or die(mysql_error())) {
session_start();
$_SESSION['username'] = $suser;
header("Location: loggedin.php");
} else {
echo "<div class=\"warning\"><span>Some Error occured durring processing your data</div>";
}
}
}
if(mysql_num_rows(mysql_query($find))=="1"or die(mysql_error())){
If wrong password is entered, mysql_num_rows(mysql_query($find)) is 0 so it results in die(mysql_error()). But since there is no mysql_error(), you see a blank page.
Try this
$result = mysql_query($find) or die(mysql_error());
if (mysql_num_rows($result) == 1) {
// proceed
} else {
// authentication failed
}
EDIT: This is just for illustration purpose only. Use MySQLi or PDO when dealing with MySQL.
The code is little bit confusing for me, consider using this code.
<?php
include('db.php');
if(isset($_POST['login'])) {
$username = mysql_real_escape_string($_POST['user']);
$password = md5($_POST['pass']);
if(empty($username) || empty($password)) {
echo "Empty username or password.";
} else {
mysql_query("SELECT * FROM `users` WHERE `user` = '$user' AND `password.md5` = '$password'");
if(mysql_num_rows() == 1) {
// login successfull
session_start();
$_SESSION['username'] = $username;
header("Location: loggedin.php");
} else {
echo "Invalid username or password.";
}
}
} else {
include ('form.php');
}
?>

Categories