check for several conditions when a user logs in - php

I would like to accomplish the following:
If a username or password field is null, notify the user. If user name already exists, do not insert into the database and notify user to create a different name. if the username is unique and password is not null, return the username to the user.
As of now it always returns "Please enter a different user name." I believe the issue has to do with the database query but I am not sure. If anyone can have a look and see if I am making an error, I greatly appreciate it, thanks.
if ($userName or $userPassword = null)
{
echo "Please enter a user name and password or return to the homepage.";
}
elseif (mysql_num_rows(mysql_query("SELECT count(userName) FROM logininfo WHERE userName = '$userName'")) ==1)
{
echo "Please enter a different user name.";
}
elseif ($userName and $userPassword != null)
{
echo "Your login name is: $userName";
}

if ($userName or $userPassword = null)
This checks if the $userName is true (equivalent to $userName == true), and you're assigning null to $userPassword. You want something like $userName == '' || $userPassword == ''.
"SELECT count(userName) FROM logininfo WHERE userName = '$userName'"
Risk of SQL injection. Use mysql_real_escape_string before plugging values into queries!
Also, mysql_num_rows will always return 1 row, hence this expression is always true. You need to look at the value of this one row.
elseif ($userName and $userPassword != null)
If this check was what you'd intend it to be, it'd be redundant with the first check.
Use something like this:
function validateUser($username, $password) {
if ($username == '' || $password == '') {
return 'Please enter a user name and password or return to the homepage.';
}
$query = sprintf("SELECT COUNT(*) as `count` FROM `logininfo` WHERE `userName` = '%s'",
mysql_real_escape_string($username));
$result = mysql_query($query);
if (!$result) {
trigger_error(mysql_error());
return false;
}
$result = mysql_fetch_assoc($result);
if ($result['count'] > 0) {
return 'Please enter a different user name.';
}
return "Username: $username";
}
$result = validateUser($username, $password);
if (!$result) {
// something went wrong, deal with it
} else {
echo htmlentities($result);
}
Note that this is still far from ideal code, but I hope you get the idea.

if ($userName or $userPassword = null)
should be
if (($userName == null) or ($userPassword == null))
However, I suspect you don't actually want to check if these are null. Assuming you're filling these variables from input fields, an empty text field is NOT null; it's an empty string. You can do !empty($userName) to check for an empty text field.
If you want to check two variable in single conditional, you have to write out each check separately - ($userName and $userPassword != null) won't work the way you expect it to, it should be ($userName != NULL and $userPassword != null).
Also, when you're checking if a variable is equal to something, you have to use the == operator. Otherwise, you're assigning the variable to that value, which is pretty much never what you want to do.

You might need the below. Very basic, though.
isset($_POST['username']) or die('username not given'); //#1
isset($_POST['password']) or die('password not given'); //#2
$escapedUsername = mysql_real_escape_string($_POST);
$result = mysql_fetch_array(mysql_query("SELECT count(userName) FROM logininfo WHERE userName = '$escapedUsername'"))
if ($result){
echo "Hello, $escapedUsername"; //#3
}else{
echo "Invalid Password"; //#4
}
But may I suggest something different. Will require you to change some portions of your app though.
have this file as some login.php
Use this for login/password reset/register/etc..
have a GET to differentiate between these requests
Use AJAX.
In that case replace the following something like the below:
#1 : die('{"RESULT":"ERROR", "DESC" : "USERNAME NOT GIVEN"}');
#2 : die('{"RESULT":"ERROR", "DESC" : "PASSWORD NOT GIVEN"}');
#3 : die('{"RESULT":"ERROR", "DESC" : "INVALID USERNAME/PWD"}');
#4 : die('{"RESULT":"SUCCESS", "DESC" : "$escapedUsername"}'); // can also use json_encode($result) here.
These are just my suggestions. I have assumed mysql doesnt give you any problem. :-)

Related

Why is this PHP-code incorrect?

This is the code which shows the errors that have to be showed in my log in-system:
<?php
include 'session.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'Please enter a username and password.';
} else if (user_exists($username) === false) {
$errors[] = 'The username or password is incorrect.';
}
print_r($errors);
}
?>
And this is the code that performs the query on the database, the function 'user_exists' which I used in the code above.
<?php
function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(customerNumber) FROM customers WHERE username = '$username'"), 0) == 1) ? true : false;
}
?>
So when the username/password-combination is wrong, login.php should obviously say 'The username or password is incorrect.'. However, when I try to log in with the correct username and password (from my database), it also says 'The username or password is incorrect.'. So what is wrong with this code?
If i understand your problem correctly,this line makes you the real problem, it always returns false from here because your customer count on row 0 is not equal to 1, so every time it returns false.
return (mysql_result(mysql_query("
SELECT COUNT(customerNumber) FROM customers WHERE
username = '$username'"), 0) == 1) ? true : false;
From PHP Manual User Notes
mysql_result() will throw E_WARNING if mysql_query returns 0 rows.
This is unlike any of the mysql_fetch_* functions so be careful of
this if you have E_WARNING turned on in error_reporting(). You might
want to check mysql_num_rows() before calling mysql_result()
As Per Comment:
function user_exists($username) {
$username = sanitize($username);
$result=mysql_result(mysql_query("SELECT COUNT(customerNumber) FROM customers WHERE username = '$username'"), 0);
print $result; //see what it returns
die(); //remove this line after your debugging.
return ($result == 1) ? true : false;
}

How to make an else condition work in PHP?

I have written PHP code with many nested if conditions. I just want to display an alert for an exceptional condition along with the if conditions.
Here is my source code:
$username = $_POST['username'];
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
$query ="SELECT * FROM user where username='.$username.' AND pass='.$password.'";
$row = mysql_fetch_array($query);
$counted = mysql_num_rows($query);
if (($counted === 1) &&
($row['username'] === $username) &&
($row['password'] === $password))
{
session_destroy();
session_start();
echo "message";
} else {
do_alert("Exceptional alert");
}
} else {
do_alert("Exceptional alert");
}
These two else conditions are not working. I don't know really where my mistake is.
I think it may have to do with your do_alert down in your code. Follow me through the code.
$username = $_POST['username'];
$password = $_POST['password'];
if (!empty($username) && !empty($password)) { // if not empty
$query =""; // this is an empty query
$row = mysql_fetch_array($query); // returns nada
$counted = mysql_num_rows($query); // gives nada back
if (($counted === 1) && ($row['username'] === $username) && ($row['password'] === $password)) { // completely useless at this point cause no row is returned
session_destroy();
session_start();
echo "message";
} else { // this will not be executed
do_alert("Exceptional alert");
}
} else { // this will be executed
do_alert("Exceptional alert"); // where is this function defined?
}
okay i commented on your code where it goes wrong. As you see it happens already on the first if, so it should return the last else. Since I dont know where your do_alert code is defined, my guess is that this is your error.
Try replacing it first with an echo like this: echo "I am a super duper evil monkey"; and see if that works.
edit
since you added your query now, i 'd like to point out as well that you should sanitize your input. This to make it more safe. However the term safe here is kind of irralevant, cause you re using an outdated mysql set. (mysqli / pdo are the ways to go now)
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
why? simple. Look at this!
$_POST['username'] = 'awesome';
$_POST['password'] = "' OR ''='";
it would turn up something then like this.
SELECT * FROM users WHERE user='awesome' AND password='' OR ''=''
And this would mean, everybody could log in, cause blank is always blank. Just as a headsup.
More information here: http://php.net/manual/en/function.mysql-real-escape-string.php
edit 2
// very first thing you do if you work with sessions, is actually starting it. you dont do this in your if else statement, cause you could not benefit of the session variable on a later stage on this page.
session_start();
// these variables come from a form with a form name, so we are going to do a check if indeed this came from that form.
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if (!empty($username) &&
!empty($password)) {
$query ="SELECT name, password FROM user WHERE name='".$username."' AND password = '".$password."'";
$row = mysql_fetch_array($query);
$counted = mysql_num_rows($query);
if (($counted === 1) &&
($row['username'] === $username) &&
($row['password'] === $password)) {
echo "message";
} else {
echo "no entrees found";
}
} else {
echo "failed to input some variable";
}
I cleaned some up in my own words, you may have to fiddle with the query, and further i fixed it a bit since you didnt use the session appropiately.
Now where it echo's the message, you should set a session variable, that you can destroy later when you log out. A session variable you can call in the session itself, on every page that has sessionstart() in it. Here you can check if it excists, if so then you are logged in. I hope this helps you out.

PHP If logic being skipped?

I'm having some problems with this login script, I've already had someone else look it over for me and we cannot seem to figure out what the issue is.
What's happening is when a user tries to login, if the the username is correct it will check if the password is correct and if the password is correct it updates the last access date and redirects like it is supposed to. However if the username is correct and the password is incorrect. It should empty out the password, and let the user know the password they entered is incorrect.
What actually happens when the password is incorrect, is it is skipping to the outermost else statement, and emptying out the username and password and saying there is an issue...whether or not the username entered is correct (regardless of whether or not the password is right).
I have no idea what is happening here, and hopefully someone can help me shed some light on it.
Thank you!
$selectUser = pg_prepare($dbConnection, "selectuser_query", 'SELECT * FROM users WHERE user_id = $1 AND password = $2');
<?php
$error = "";
$username_error = "";
$password_error = "";
if($_SERVER["REQUEST_METHOD"] == "GET")
{
$login = "";
$password = "";
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
$login = trim($_POST["login"]);
$password = trim($_POST["password"]);
if(!isset($login) || $login == "")
{
$username_error = "You must enter your user name to login!";
}
if (!isset($password) || $password == "")
{
$password_error = "You must enter your password to login!";
}
if(($error == "") && ($password_error == "") && ($username_error == ""))
{
$selectUser = pg_execute($dbConnection, "selectuser_query", array("$login", "$password"));
if($login == pg_fetch_result($selectUser, "user_id"))
{
if($password == pg_fetch_result($selectUser, "password"))
{
$date = date("n-j-Y");
$updateDateAccess = pg_execute($dbConnection, "updatedate_query", array("'$date'", "$login"));
header('Location: ./welcome.php');
}
else
{
$password = "";
$error = "The password is incorrect. Please try again.";
}
}
else
{
$login = "";
$password = "";
$error = "The username/password is incorrect. Please try again.";
}
}
}
?>
Your problem is your query:
SELECT * FROM users WHERE user_id = $1 AND password = $2
It checks both the username and password, which results in no records being returned if the password is incorrect. Thus, the next if condition isn't satisfied:
$selectUser = pg_execute($dbConnection, "selectuser_query", array("$login", "$password")); // no records
if($login == pg_fetch_result($selectUser, "user_id")) // not satisfied, because there are no records
{
// ...
}
else // this runs
{
$login = "";
$password = "";
$error = "The username/password is incorrect. Please try again.";
}
What you want to do is run a query that retrieves the (salted and hashed) password for a given username, then check the password in your application logic.
Also, as others have pointed out in the comments, this is not a good way to store passwords or respond to incorrect info. It looks like the passwords are in plain text, but they should be hashed and salted. Also, you should not tell the user which part of the information was incorrect; otherwise, you let an attacker determine valid usernames and then focus on brute-forcing those.

Login Check User Exists and is Set to Active

I have been trying to get the below code working for a few hours now. The idea is that it checks my database (b00543346) and the table "members" to see if a user exists (thus if their memberID is there. It then checks if a user is set to active.
At present not matter what username/password i enter and press login, this is displayed "Array ( [0] => Username Not Found. Have You Registered? )"
<?php
function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query ("SELECT COUNT (`membersID`) FROM `members` WHERE `username` = '$username'"), 0) == 1) ? true : false; //check if user id exists
}
function user_active($username) {
$username = sanitize($username);
return (mysql_result(mysql_query ("SELECT COUNT (`membersID`) FROM `members` WHERE `username` = '$username' AND `active` = 1"), 0) == 1) ? true : false; //check if user has activated account
}
?>
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'You Must Enter a Username AND Password';
} else if (user_exists($username) === false) {
$errors[] = 'Username Not Found. Have You Registered?';
} else if (user_active($username) === false) {
$errors[] = 'You Haven\'t Activated Your Account, Please Do So!';
}
print_r($errors);
}
?>
EDIT: mysql functions in PHP do not like a space between the function name and the first open parenthesis. So count(membersID) will work, while count (membersID) will get you an error!
I'm curious what your sanitize() function is doing. If it at all modifies the username, it seems likely that your initial test data was input into the table manually and not run through the sanitize() function, then as the code sanitizes and perhaps modifies the data, it's not matching in the SQL.
You may also add some debug to your function to see a bit better what is going on. The current function is obfuscating some of what is happening. Try:
function user_exists($username) {
print "DEBUG: username=[$username]\n";
$query = "SELECT COUNT (`membersID`) FROM `members` WHERE `username` = '$username'";
print "DEBUG: query=$query\n";
$result = mysql_query($query);
if (!$result) {
die('Could not execute query:' . mysql_error());
}
print "DEBUG Result Set Array\n";
print_r(mysql_fetch_assoc($result));
print "DEBUG just the result now\n";
print mysql_result($result, 0);
return mysql_result($result, 0) == 1;
}
I'm not too fond of the standard SQL functions of PHP anymore, so I can't judge that. But have you tried
SELECT COUNT (*) FROM `members` WHERE `username` = '$username'

php user login anf function

if(isset($_POST['login'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if(empty($username) || empty($password)) {
$error = 1;
$error_message = 'Please fill in all the required fields.';
} else {
get_login_name($username, $password);
//The commented line works...
//$query = mysql_query("SELECT /* user_logged true, page login */username, password FROM members WHERE username = '".$username."' AND password = '".sha1($password)."' LIMIT 1");
}
if(mysql_num_rows(get_login_name($username, $password)) == 0) {
echo get_login_name($username, $password);
$error = 1;
$error_message = 'Incorrect username or password.';
} elseif ($error == 0) {
//Other stuff....
}
}
Function:
function get_login_name($password, $username) {
global $myDB;
global $config;
$query = "SELECT /* page == login, functions.php */username, password FROM members WHERE username = '".$username."' AND password = '".sha1($password)."' LIMIT 1";
$result = $myDB->Execute($query) or die(GetDbError($myDB->ErrorMsg()));
return $result;
}
How properly check if username or password incorrect ? (part if(mysql_num_rows(g.....)
In my opinion something wrong i have done ir function get_login_name with return and checking. By the way, using adodb.
EDIT:
After all i decided a bit test it, so, let's leave function as it now and let's check username and password part:
if (!is_null(get_login_name($password, $username))) {
echo get_login_name($password, $username);
$error = 1;
$error_message = 'Incorrect username or password.';
}
If username or password incorrect ir gives me:
username,password which mean result doesn't found at all (no user, if user correct gives same)
Ok, let's enter valid user and pass, and it gaves:
username,password zero,0a706ce75f3bc195c8ed7be5a21d3766abb0d384
What's wrong ?
Essentially, if get_login_name has a return, that means the query returned a match for username and password which means the combination is correct, otherwise, no result means there's no match so you could say either username or password is incorrect (because they don't exist or one of them is wrong). If $Result has a value using get_login_name would likely to be just:
if (!is_null(get_login_name($password, $username)))
// correct
else
// incorrect
Play around with it and see the results.
Ech, after testing managed it to work :)
That seems this part fails :/
if (!is_null(get_login_name($password, $username)))
So, hole code:
if (!$myDB->Affected_Rows()) {
//if(mysql_num_rows($query) == 0) {
$error = 1;
$error_message = 'Incorrect username or password.';
}
What i have ? Just changed it to:
if (!$myDB->Affected_Rows()) {
Thank you all guys who tryed help.

Categories