Use SQL to check if user exists in database - php

I'm trying to check a table called members to see if a user exists with it's email and password. I'm able to connect to the database, but for some reason, it jumps all these if statements and echoes 'You have been logged in!' even when I put the wrong email or password? Here is the html and php:
<form action="/login-user" method="POST">
Email: <input type="text" name="login_email"><br>
Password: <input type="password" name="login_password"><br>
<button type="submit">Login</button>
</form>
PHP:
<?php
session_start();
/*error_reporting(0);*/
require 'users/functions/user-functions.php';
require 'users/connect-database.php';
if (empty($_POST) === false) {
$email = mysqli_real_escape_string($connection, $_POST['login_email']);
$password = stripslashes(mysqli_real_escape_string($connection, $_POST['login_password']));
$encrypted_password = md5($password);
if (empty($email)) {
echo 'You need to enter an email<br>';
} else if (empty($password)) {
echo 'You need to enter a password<br>';
} else if(user_exists($connection, $email, $encrypted_password) === false) {
echo 'You don\'t seem to be registered?';
} else if (user_active($connection, $email, $encrypted_password) === false) {
echo 'You haven\'t activated your account!';
} else {
$login = login($connection, $email, $encrypted_password);
if ($login === false) {
echo 'That email/password combination is incorrect';
} else {
$_SESSION['user_id'] = $login;
$_SESSION['logged_in'] = true;
echo 'You have been logged in!';
}
}
/*print_r($errors);*/
} else {
echo 'inputs were empty<br>';
}
require 'users/disconnect-database.php';
?>
Content of the file 'user-functions.php':
<?php
function sanitize($connection, $data) {
return mysqli_real_escape_string($connection, $data);
}
function logged_in() {
return $_SESSION['logged_in'];
}
function user_exists($connection, $email, $password) {
$query = mysqli_num_rows(mysqli_query($connection, "SELECT * FROM members WHERE email = '$email' AND password = '$password'"));
return ($query > 0) ? true : false;
}
function user_active($connection, $email, $password) {
$query = mysqli_query($connection, "SELECT user_id FROM members WHERE email = '$email' AND password = '$password' AND `active` = 1");
return ($query !== false) ? true : false;
}
function return_user_id($connection, $email, $password) {
return mysqli_query($connection, "SELECT user_id FROM members WHERE email = '$email' AND password = '$password'");
}
function login($connection, $email, $password) {
/*$user_id = mysql_result(mysqli_query($connection, "SELECT user_id FROM members WHERE email = '$email' AND password = '$password'"), 0, 'user_id');*/
/*$password = md5($password);*/
$query = mysqli_query($connection, "SELECT user_id FROM members WHERE email = '$email' AND password = '$password'");
/*return (mysqli_query($connection, $query) or die (false));*/
if ($query === false) {
return false;
} else {
return $query;
}
/*return ($query !== false) ? true : false;*/
}
function log_out() {
unset($_SESSION['logged_in']);
session_unset();
session_destroy();
}
?>
If the answer is using mysql_result or mysqli_result, please explain in full detail because even after reading on the manual and W3Schools and everywhere else, I still don't understand how those functions work.
Thanks for any answers, and by the way, I have read all the other posts about this stuff but I didn't find any answers. Thanks.

First of all I would really advise to use a sha for encrypting passwords because md5 is decrypted in no time at all.
for your login function try the following:
<?php
function login($connection, $email, $password) {
$query = mysqli_query($connection, "SELECT `email`, `password` FROM `members` WHERE `email` = '$email' AND `password` = '$password'");
$count = mysqli_num_rows($query); //counting the number of returns
//if the $count = 1 or more return true else return false
if($count >= 1) {
return true;
} else {
return false;
}
}
?>
after the script has returned true you could set a session or do what you need to do with it.
EDIT You need session_start in every file so the best thing to do is include this.
I hope this works I typed it realy fast so there might be some errors in it but please let me know:
<?php
function generate($password) {
$password = hash('sha1', $password);
return $password;
}
function login($connection, $email, $password) {
$password = generate($password);
$query = mysqli_query($connection, "SELECT `email`, `password` FROM `members` WHERE `email` = '$email' AND `password` = '$password'");
$count = mysqli_num_rows($query); //counting the number of returns
//if the $count = 1 or more return true else return false
if($count >= 1) {
return true;
} else {
return false;
}
}
function exists($connection, $detail, $table, $row, $value) {
$query = mysqli_query($connection, "SELECT `$detail` FROM `$table` WHERE `$row` = '$value'");
$count = mysqli_num_rows($query);
if($count >= 1) {
return true;
} else {
return false;
}
}
function detail($connection, $detail, $table, $row, $value) {
$query = mysqli_query($connection, "SELECT `$detail` FROM `$table` WHERE `$row` = '$value'");
$associate = mysqli_fetch_assoc($query);
return $associate[$detail];
}
function errors($error) {
echo '<ul class="error">';
foreach($error as $fault) {
echo '<li>'.$fault.'<li>';
}
echo '</ul>';
}
function isLoggedIn() {
if(!empty($_SESSION['logged_in']) && exists($connection, 'id', 'members', 'id', $_SESSION['logged_in']) == true) {
return true;
} else {
return false;
}
}
function logout() {
unset($_SESSION['logged_in']);
}
if($_POST) {
$email = mysqli_real_escape_string($connect, strip_tags($_POST['email']));
$password = mysqli_real_escape_string($connect, strip_tags($_POST['password']));
if(!empty($email) && !empty($password)) {
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error[] = 'Your email: '.$email.' is not valid';
}
if(exists($connection, 'email', 'members', 'email', $email) == false) {
$error[] = 'You are not registered';
}
if(detail($connection, 'active', 'members', 'email', $email) != 1) {
$error[] = 'Your account is not activated';
}
if(empty($error)) {
$query = login($connection, $email, $password);
if($query == true) {
$_SESSION['logged_in'] == detail($connection, 'id', 'members', 'email', $email);
}
}
} else {
$error[] = 'There are empty fields';
}
if(!empty($error)) {
echo errors($error);
}
}
?>
<form action="" method="POST">
Email: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>

Related

Why does my foreach loop not get executed?

I made a login form. The form works and after the user inputs the right email and password, access is granted. There is an issue.
I use a foreach loop to test all results (should be one account).
foreach ($result as $outp) {
$role = $outp->role;
$name= $outp->name;
$surname= $outp->surname;
$_SESSION["name"] = $name;
$_SESSION["surname"] = $surname;
$_SESSION["role"] = $role;
if($_SESSION["role"] == 'Admin') {
header("location:index.php");
} else
if($_SESSION["role"] == 'User') {
header("location:../index.php");
} else {
header("location:login.php");
}
}
This code is supposed to check for the account role, and determine which page it can go to.
The issue is that everything inside of the foreach loop does not get executed.
Here you see the full code including the foreach loop (only php):
if(isset($_POST["login"]))
{
if(empty($_POST["email"]) || empty($_POST["password"]))
{
$message = '<label>Some fields are still empty</label>';
}
else
{
$query = "SELECT * FROM account WHERE email = :email AND password= :password";
$statement = $con->prepare($query);
$statement->execute(
array(
'email' => htmlspecialchars($_POST["email"]),
'password' => htmlspecialchars($_POST["password"])
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["email"] = $_POST["password"];
$username = $_SESSION["email"];
$query = "SELECT role, name, surname FROM account WHERE email = :email";
$stm = $con->prepare($query);
$stm->bindParam(':email', $email, PDO::PARAM_STR, 20);
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $pers) {
$rol = $pers->rol;
$voornaam = $pers->voornaam;
$achternaam = $pers->achternaam;
$_SESSION["voornaam"] = $voornaam;
$_SESSION["achternaam"] = $achternaam;
$_SESSION["rol"] = $rol;
if($_SESSION["rol"] == 'Admin') {
header("location:index.php");
} else
if($_SESSION["rol"] == 'Gebruiker') {
header("location:../index.php");
} else {
header("location:login.php");
}
}
}
else
{
$message = '<label>Wrong input</label>';
}
}
}
$email is used in SQL but no where declared or assigned.
if($count > 0)
{
$_SESSION["email"] = $_POST["email"];
$email = $_SESSION["email"];
$query = "SELECT role, name, surname FROM account WHERE email = :email";
$stm = $con->prepare($query);
$stm->bindParam(':email', $email, PDO::PARAM_STR, 20);
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $pers) {
$rol = $pers->rol;
$voornaam = $pers->voornaam;
$achternaam = $pers->achternaam;
$_SESSION["voornaam"] = $voornaam;
$_SESSION["achternaam"] = $achternaam;
$_SESSION["rol"] = $rol;
if($_SESSION["rol"] == 'Admin') {
header("location:index.php");
} else
if($_SESSION["rol"] == 'Gebruiker') {
header("location:../index.php");
} else {
header("location:login.php");
}
}
}
else
{
$message = '<label>Wrong input</label>';
}
}
Something wrong here in your code.. why assign posted password value to email?
$_SESSION["email"] = $_POST["password"];
$username = $_SESSION["email"];

Login page is not working

I am uploading my website in a web server and my login is not working.On localhost everything was fine.Now when i put the correct username and password it gives me That username/password combination is incorrect.When i put the incorrect password it give this again.The other validations work fine and my code :
log in.php
<?php
include 'core/init.php';
if(empty($_POST) === false) {
$username= $_POST['username'];
$password = $_POST['password'];
if(empty($username)=== true || empty($password) === true ) {
$errors[] = 'You need to enter a username & password';
}else if (user_exists($username) === false) {
$errors[]='We cant find that username.Have you registered?';
}else if (user_active($username) === false) {
$errors[]='You havent activated your account!';
}else {
if(strlen($password) > 32) {
$errors[] = 'Password too long';
}
$login = login($username, $password);
if($login === false) {
$errors[] = 'That username/password combination is incorrect';
}else{
$_SESSION['user_id'] = $login;
header('Location: index2.php');
exit();
}
}
}else {
$errors[] = 'No data received';
}
include 'overall/headerr.php';
if (empty($errors)=== false) {
?>
<h2>We tried to log you in, but...</h2>
<?php
echo output_errors($errors);
}
?>
users.php
function login($username, $password){
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username`='$username' AND `password`='$password'"), 0)==1) ? $user_id : false;
}
function logged_in() {
return (isset($_SESSION['user_id'])) ? true : false;
}
function user_exists($username) {
$username = sanitize($username);
return (mysql_result( mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` ='$username' "), 0) == 1) ? true : false;
}
function user_active($username) {
$username = sanitize($username);
return(mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `active` =1"), 0) == 1) ? true : false;
}
function user_id_from_username($username) {
$username = sanitize($username);
return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id');
}
general.php
<?php
function sanitize($data) {
return mysql_real_escape_string($data);
}
function output_errors($errors) {
$output = array();
foreach($errors as $error) {
$output[] = '<li>'. $error .'</li>';
}
return '<ul>' . implode ('', $output) . '</ul>';
}
?>
init.php
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array() ;
?>
Why are you making your code long & complicated?
I use this simple and nice code:
<?php
session_start(); /* Start a session on browser */
require('connect.php'); /* Get database-connection script */
$username = $_POST['username']; /* Define variable ' $username ' */
$password = $_POST['password']; /* Define variable ' $password ' */
/* Check if username or password is empty */
if(empty($username) || empty($password)) {
/* If one of the fields are empty, send user back. */
echo 'afar'; // All fields are required
} else {
/* Select usernames & passwords from our database */
$check_accpass = $dbh->query('SELECT username,password FROM `users` WHERE `username`='.$dbh->quote($username).' AND `password`='.$dbh->quote($password).'')->fetchAll();
/* Check if username & password has any matches in our database */
if($check_accpass) {
echo 'success';
/* IF they do, set $username to $_SESSION['USERNAME'] and same with password */
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
// Set cookies
// name, value, expire, path, domain, secure, httponly
setcookie("username", $username, time() + (172800 * 30), "/", NULL, TRUE, TRUE); /* 2 days = 48 hours */
setcookie("password", $password, time() + (172800 * 30), "/", NULL, TRUE, TRUE); /* 2 days = 48 hours */
// Send user to root
header('location:/');
} else {
/* if no matches are found, print the text below */
echo 'wuop'; // wrong username or password
}
}
?>

pull from session user info

ok I have a user login that uses email address and password when they login I want to pull there session data
like username and anything else from there record
I use this
<?php
if(isset($_SESSION['email'])) {
echo $_SESSION['email'];
}
?>
it works and pulls there email address but how do I get there username? I tried changing email to username and nothing shows
my login setup
/* login functions */
function login_user($email, $password, $remember)
{
$sql = "SELECT user_pwd, uid FROM users WHERE user_email = '" . escape($email) . "' AND active = 1";
$result = query($sql);
if (row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['user_pwd'];
if (password_verify($password, $db_password)) {
if ($remember == "on") {
setcookie("email", $email, time() + 86400,'/');
}
$_SESSION['email'] = $email;
return true;
} else {
return false;
}
return true;
} else {
return false;
}
}
/* User Logged in Function */
function logged_in(){
if (isset($_SESSION['email']) || isset($_COOKIE['email'])) {
return true;
} else {
return false;
}
}
You need to make small changes in login_user() function.
function login_user($email, $password, $remember)
{
$sql = "SELECT user_pwd, uid, username FROM users WHERE user_email = '" . escape($email) . "' AND active = 1";
$result = query($sql);
if (row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['user_pwd'];
if (password_verify($password, $db_password)) {
if ($remember == "on") {
setcookie("email", $email, time() + 86400,'/');
}
$_SESSION['email'] = $email;
$_SESSION['username'] = $row['username'];
return true;
} else {
return false;
}
return true;
} else {
return false;
}
}
Now you can use below code to get username in session. But make sure you must have username field in users table.
if(isset($_SESSION['username'])) {
echo $_SESSION['username'];
}

cannot log in with correct password and username. keep false

when I log in, even the password and username are correct, it keep error.
Array ( [0] => That user/password combination is incorrect )
the username and password is active and existed.
login.php
<?php
include 'init.php';
if(empty($_POST) === false){
$username = $_POST['username'];
$password = $_POST['pwd1'];
if(empty($username)|| empty($password)) {
echo 'You need to enter username and password';
}
else if(user_exists($username) === true){
if(user_active($username) === true){
$login = login($username, $password);
if($login === false){
$errors[] = 'That user/password combination is incorrect' ;
} else{
$_SESSION['user_id'] = $login;
ob_end_clean();
header('Location:forum.php');
exit();
}
}
else{$errors[] = 'You haven\'t activated your account!';}
}
else{$errors[] = 'We can\'t find that username. Have you registered?';}
print_r($errors);
}
?>
users.php
<?php
function logged_in(){
return (isset($_SESSION['user_id'])) ? true :false;
}
function user_exists($username){
$username = sanitize($username);
$sql = "SELECT COUNT(user_id) FROM `user` WHERE username = '$username'";
$result = mysql_query( $sql);
return (mysql_result($result,0) ==1) ? true : false;
}
function user_active($username){
$username = sanitize($username);
$sql ="SELECT COUNT(user_id) FROM `user` WHERE username = '$username' AND `active` = 1";
$result = mysql_query( $sql);
if ($result === false){
return false;
}
return (mysql_result($result,0) ==1) ? true : false;
}
function user_id_from_username($username){
$username = sanitize($username);
$sql = "SELECT user_id FROM `user` WHERE username = '$username'";
$result = mysql_query( $sql);
if ($result === false){
return false;
}
return mysql_result($result,0, 'user_id');
}
function login($username, $password){
$username = sanitize($username);
$password = md5($password);
$query = mysql_query("SELECT COUNT(user_id)
FROM `user`
WHERE username ='$username' AND pwd1 ='$password'");
$row = mysql_fetch_row($query);
if($row[0]>0){
return user_id;
}else{
return false;
}
}
?>
general.php
<?php
function sanitize($data){
return mysql_real_escape_string($data);}
?>
init.php
<?php
ob_start();
session_start();
require 'connect.php';
require 'general.php';
require 'users.php';
$errors = array();
?>
You don't assign $login to $_SESSION['user_id'], because you call die($login); before that, which is same as exit, nothing is parsed after that. Change the order.
And pray that your sanitize function works. Anyway, you had better switch to PDO, because mysql_ functions are deprecated and not safe. Even if you sanitize your $_POST and $_GET, you can still have malicious values selected from your database or from XML you parse or from other source.

login form email and password incorrect error

I created a login form but when i try to login, it says email or password is incorrect but I'm going in the right email and password.
I create user in my database users table but again again i get this error. All error is ok when i try to emtpy email and password it says You need to entere a email and password.
and activated error also ok.I am entering the correct password and email address. Gives me the error.
This is users.php
<?php
function user_exists($email) {
$email = sanitize($email);
return (mysql_result(mysql_query("SELECT COUNT(`id`) FROM `users` WHERE `email` = '$email'"), 0) == 1) ? true : false;
}
function user_active($email) {
$email = sanitize($email);
return (mysql_result(mysql_query("SELECT COUNT(`id`) FROM `users` WHERE `email` = '$email' AND `active` = 1"), 0) == 1) ? true : false;
}
function user_id_from_email($email) {
$email = sanitize($email);
return mysql_result(mysql_query("SELECT `id` FROM `users` WHERE `email` = '$email'"), 0, 'id');
}
function login($email, $password) {
$id = user_id_from_email($email);
$email = sanitize($email);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT (`id`) FROM `users` WHERE `email` = '$email' AND `password` = '$password'"), 0 ) == 1) ? $id : false;
}
?>
And this is login.php
<?php
include("core/init.php");
if(empty($_POST) === false) {
$email = $_POST['email'];
$password = $_POST['password'];
if (empty($email) === true || empty($password) === true) {
$errors[] = 'You need to enter a email and password';
} else if (user_exists($email) === false) {
$errors[] = 'We can\'t find that email. Have you registered ?';
} else if (user_active($email) === false) {
$errors[] = 'You have\'t activated your account';
} else {
$login = login($email, $password);
if ($login === false) {
$errors[] = 'That email/passowrd cocmbination is incorrect';
}else {
$_SESSION['id'] = $login;
header('Location: main.php');
exit();
}
}
print_r ($errors);
}
?>
Sorry, but there's a whole load of stuff which is wrong - lots of it may be producing errors.
1) there is no 'sanitize' function in php and you haven't told us what it does.
2) your login.php does niclude users.php
3) generating an md5 hash of the password is far from secure (it should be a slated sha1 hash as a minimum)
4) you never check for errors being returned by the DBMS
5) ...actually - that's not true - you compare the return value from the functions in users.php to false - and you'll only get false if the query fails - not if it returns 0 rows
Consider....
function do_something_with_email($email, &$err) {
$email = mysql_real_escape_string($email);
if (!($res=mysql_query("SELECT `id` FROM `users` WHERE `email` = '$email'"))) {
$err=mysql_error();
return false;
}
if (!($data=mysql_fetch_array($res)) {
$err=mysql_error();
return false;
}
return $data[0];
}
switch (do_something_with_email($email, $err)) {
case false:
die ($err);
case 0:
print "No records matched";
break;
default:
print "OK";
break;
}

Categories