Why is this PHP-code incorrect? - php

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

Related

Cannot add to mySQL database using XAMPP for mac

I hello I am currently trying to add data to my user login database however for some reason my database it not being updated when I register a new user.
here is my code from user.inc.php:
<?php
//checks if username already exists in database
function user_exists($user)
{
$user = mysqli_real_escape_string($user);
$total = mysqli_query("SELECT user_id FROM user_system WHERE user_name= ('$user')");
return (mysql_result($total, 0) == '1') ? true : false;
}
//checks if username and password combo is valid
function valid_credent($user, $pass)
{
$user = mysqli_real_escape_string($user);
$pass = sha1($pass);
$total = mysqli_query("SELECT COUNT user_id FROM users
WHERE user_name = '$user' AND
user_password = '$pass' ");
return(mysql_result($total, 0) == '1') ? true : false;
}
//add user to database
function add_user($user, $pass)
{
$user = mysqli_real_escape_string(htmlentities($user));
$pass = sha1($pass);
$queryStr = "INSERT INTO users (user_name, user_password) VALUES ('$user', '$pass')";
$R = mysqli_query($mysqli,$queryStr);
}
?>
I also have warning on my register page when I try to add view errors
Warning: mysql_result() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/PostalCloud/core/user.inc.php on line 8
line 8:
return (mysql_result($total, 0) == '1') ? true : false;
I have tried using "sanitize()" however that doesn't exists.
UPDATE: Still getting errors after modifying code. Here part of my register.php code and I have a init.inc.php that uses mysqli to connect to database.
<?php
include('init.inc.php');
$errors = array();
if(isset($_POST['username'], $_POST['password'], $_POST['repeatPassword']))
{
if(empty($_POST['username']))
{
$errors[] = 'The username cannot by empty. ';
}
if(empty($_POST['password']) || empty($_POST['repeatPassword']))
{
$errors[] = 'The password cannot by empty. ';
}
if($_POST['password'] !== $_POST['repeatPassword'])
{
$errors[] = 'Password verification failed. ';
}
if(user_exists($_POST['username']))
{
$errors[] = 'The username you entered is already taken. ';
}
if(empty($errors))
{
add_user($_POST['username'], $_POST['password']);
$_SESSION['username'] = htmlentities($_POST['username']);
header('Location: protected.php');
die();
}
}
?>
init.inc.php:
<?php
session_start();
$exceptions = array('register', 'login');
$page = substr(end(explode('/',$_SERVER['SCRIPT_NAME'])), 0, -4);
if(in_array($page, $exceptions) === false)
{
if(isset($_SESSION['username']) === false)
{
header('Location: login.php');
die();
}
}
$mysqli = mysqli_connect('localhost','root','', 'user_system');
$path = dirname(__FILE__);
include("{$path}/core/user.inc.php");
?>
The problem is that mysql_query() is returning a boolean instead of a result resource. There are two reasons this can happen:
You performed query that returns success/fail instead of a result
set (e.g. UPDATE)
Your query failed
your query contains single quotes on column names..this should be removed :
$total = mysqli_query("SELECT user_id FROM user_system WHERE user_name= '$user'");

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'

cannot login when username and password are correct

Hello so I am doing this tutorial from php academy for a php and mysql login and registration form. It was going okay.. he was showing how to idk what the correct way to say it but to create functions to echo errors.. yeah that sounds right. So the first couple errors echoed correctly but the one to actually validate the user_id and whatknot, isn't working. Its showing the error I created when the username and password combination is incorrect even when i submit the correct information. I've created a few dummy users and none of them can get through.
this is my code..
include 'core/init.php';
include 'includes/overall/header.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'Uh oh! You forgot to enter your username and password';
} else if (user_exists($username) === false) {
$errors[] = 'Who is that? Have you registered?';
} else if (user_active($username) === false) {
$errors[] = 'Account is not activated.';
} else {
$login = login($username, $password);
if ($login === false) {
$errors[] = 'That username and password combination is incorrect';
} else {
$_SESSION['user_id'] = $login;
header('Location:index.php');
exit();
}
}
print_r($errors);
}
include 'includes/overall/footer.php';
and
function logged_in() {
return (isset($_SESSION['user_id'])) ? true : false;
}
function user_exists($username) {
$username = sanitize($username);
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
return (mysql_result($query, 0) == 1) ? true : false;
}
function user_active($username) {
$username = sanitize($username);
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `active` = 1");
return (mysql_result($query, 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');
}
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
$query = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'");
return (mysql_result($query, 0) == 1) ? $user_id : false;
}
does anyone know what I am doing wrong? I've tried a few things and nothing works. For example in the video he does it a little different and puts his queries in line but that was giving me errors so i did it the way he originally had it and made the queries variables (i only have somewhat of an idea what I'm actually saying haha).. but that fixed the errors. I tried doing that to the other functions (not shown) but that caused a whole lot of errors :(
is it something really dumb? I had a similar problem before that I figured out was due to a missing semi colon but I've stared at this stupid code for so long and haven't found anything.. I re-watched the videos in the tutorial series that explain all this like 10 times each.. my eyes feel like they are going to bleed or explode. Some of the comments show that others are having similar issues.. help?
I'm new to all this php mysql stuff so.. I wont be offended if u speak to me like a child.. in fact its appreciated.
thanks.
Do I understand correctly that you are unable to login now?
I had similar problems in the past. I do not see your mistake but I will share a method that allowed me to find mistakes.
Store the MySQL query in a variable as a string and data inputted from a form
echo that variable
Test the outputted string in phpMyAdmin - if the query is wrong it will give you a hint what is wrong with it.
Also it might be worth testing the queries with "LIKE" instead of "="
eg.
.....FROM `users` WHERE `username` LIKE '$username'.....
This is my code:
function user_exists($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT * FROM `users` WHERE `username` = '$username' "),0) ==1) ? true : false;
}

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.

check for several conditions when a user logs in

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. :-)

Categories