i'm playing around and trying to incorporate a nested function into my login script. The functions are all below. Also, beneath my functions is the portion of the login script im trying to incorporate them in. However, everytime I try to log in, it says invalid username. However if I user function a and b in the login script instead of function d, everything works fine. Can some tell me where i',m going wrong? Thanks.
//a -username
function username_check($username){
$usercheck = "SELECT user_id FROM users WHERE username ='$username'";
$userqry = mysql_query($usercheck) or die ("Could not match data because ".mysql_error());
$num_rows = mysql_num_rows($userqry);
return ($num_rows == 1) ? true : false;
}
//b - password
function password_check($password, $username){
$passwordcheck = "SELECT password FROM users WHERE username ='$username'";
$passwordqry = mysql_query($passwordcheck) or die ("Could not match data because ".mysql_error());
while($retrievepassword = mysql_fetch_array($passwordqry))
{
$password = md5($password);
return ($password != $retrievepassword['password']) ? true : false;
}
}
//c -email
function email_check($email){
$emailcheck = "SELECT user_id FROM users WHERE email = '$email'";
$emailqry = mysql_query($emailcheck) or die ("Could not match data because ".mysql_error());
$num_rows = mysql_num_rows($emailqry);
return ($num_rows == 1) ? true : false;
}
//d -username + password + email check? all in one? DOESNT WORK
function user_check($username = NULL, $password = NULL, $email = NULL) {
if(($email !=NULL)) {
email_check($email);
}
elseif(($username !=NULL) && ($password!=NULL)){
password_check($password,$username);
}
elseif(($username !=NULL) ) {
username_check($username);
}
}
//LOGIN SCRIPT
if (user_check($username1) ==false) {
$logerrors[] = 'Invalid username';
}
elseif (user_check($password1, $username1)) {
$logerrors[] = 'Incorrect password';`
well for one, function d doesn't return any values.
Related
I have defined a function to check user credentials and would like it to return true if the auth passed and false if it failed. my function is defined as follows:
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
return $logged_in;
}
the problem I am running into is this, when I call the function and try to use what should be the returned value I get an error that the variable is not defined.
_userLogin($username, $password);
if ($logged_in == True){
'do something';
} else {
'do something else'
}
what am I doing wrong?
You are trying to use the variable $logged_in that is defined in function _userLogin outside the block. Assign the return value that is returned by the function like,
$logged_in = _userLogin($username, $password)
if ($logged_in == True){
'do something';
} else {
'do something else'
}
Also you will always receive TRUE because you are accessing variables $salt, $password outside the if block where they are being retrieved thus the fields not being assigned properly.
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in = false;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
$dbpass = '';
$salt = '';
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
}
}
return $logged_in;
}
PLEASE NOTE: I did not perform any logic checks other than fix your syntax
Replace your branching (where you use the function) with the simpler:
if( _userLogin($username, $password) ){
//success
}else{
//failure
}
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'");
I have a function in which if a named user is in my database, I'll have a message on my screen of a string value, that simply says my function works.
However, when I change the name to one that doesn't exist in the database, I still get a string output that says the function works. So I am trying to figure out where my logic is messed in the query. Here's what I have:
Users.php File:
<?php
function user_exists($username)
{
$db = "adults";
$dbH = "localhost";
$dbU = "root";
$dbP = "Jeffery9";
//connection to database
$dbCon = mysqli_connect($dbH, $dbU, $dbP, $db);
$username = sanitize($username);
// $query = mysqli_query($dbCon,"SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
return (mysqli_data_seek(mysqli_query($dbCon,"SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'"), 0) == 1) ? true : false;
}
?>
Now here's the login page which processes the function to see if a user actually exists:
Login.php File:
<?php
include 'core/init.php';
if (user_exists('raiders7') === true)
{
echo 'user found!';
}
die();
if(empty($_POST) === false)
{
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) === true || empty($password) === true)
{
$errors[] = 'You need to enter a username and password.';
}
else if (user_exists($username) === false)
{
$errors[] = 'We can\'t find that username. Have you registered?';
}
}
?>
Of course I have one row and one user in the database. When the string is user_exists('raiders7'), I get user found! on my index page.
But when it's user_exists('something else') it still returns user found! on the page.
How is this so? The page should be blank if the user doesn't exist.
Lastly, I'm using another function to sanitize my data like such:
General.php File:
<?php
function sanitize($data)
{
$db = "adults";
$dbH = "localhost";
$dbU = "root";
$dbP = "Jeffery9";
// connection to database
$dbCon = mysqli_connect($dbH, $dbU, $dbP, $db);
return mysqli_real_escape_string($dbCon, $data);
}
?>
Don't know if the last part is helpful, but can someone kindly help me fix my logic on how I can stop getting a user found! message, when the user doesn't exist in my test database. Thank you.
You should fetch the results to get the correct/desired result.
What happens is you just move the pointer then of course there will always be a result set row in index 0
+----------------+
| COUNT(user_id) | // even when count is zero, your condition will still be true
+----------------+
| 0 |
+----------------+
Even when the username is wrong/does not exist!
Fetch the result properly then check the count
$username = $dbCon->real_escape_string($username);
$query = mysqli_query($dbCon,"SELECT COUNT(`user_id`) as total FROM `users` WHERE `username` = '$username'");
$row = $query->fetch_assoc();
$count = $row['total']; // fetch the result!
if($count > 0) {
// true
} else {
// false
}
Or as #Fred said, just use num_rows and much better to bind it:
$sql = 'SELECT * FROM `users` WHERE `username` = ?';
$select = $dbCon->prepare($sql);
$select->bind_param('s', $username);
$select->execute();
if($select->num_rows > 0) {
// found
} else {
// not found
}
Can anyone please help me with the following error. I am making a register and login function for my website. I have it connected to my local database and in there I have created a user. When I test that I can login and that username and password is recognised, it works as expected. But I get this error
Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 17 in C:\xampp\htdocs\LoginAndRegistration\core\functions\users.php on line 34
And this is what I have on line 34
return (mysql_result(mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? true : false;
Which is part of the following function
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_result(mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? true : false;
}
Ive been staring at it for ages now but cant seem to figure out the problem. Can anyone tell me what I am doing wrong?
Thanks
That line of code looks like that you want to check does username and password exist. You need to change your code to this:
return (mysql_result(mysql_query("SELECT COUNT(id) FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? true : false;
Also change (id) to your id name of column.
This error means the query failed. Always check if the query succeeded:
$q = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
if ($q) {
if ($rows = mysql_num_rows($q)) {
// Continue operation, or set a flag
} else {
// No matching rows, throw an Exception or set a flag
}
} else {
// Something is wrong
die(mysql_error());
}
Your error probably comes from the fact that the query did not return any result at all because there was none with matching username and password.
I would really not stuff that much functions into each other. It looks overcomplicates, it does not leave any room to add error handling (like handling the case that is supposed to happen in your case), and it messes up PHP'S error reporting, because any error happening will be on the same code line.
Spread stuff out into multiple lines. It makes things clearer for you any anybody that reads your code, in enhances debugging activities, and is generally a good idea because of the lower line length.
You are getting a warning (not an error) because mysql_query at some times, it won't return any rows, so trying to get the first row with mysql_result when there are not rows, will raise the warning.
You can try:
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
$query = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
if (mysql_num_rows($query) > 0)
return true;
else
return false;
}
With the depreciation argument aside, use mysql_num_rows instead of mysql_result.
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_num_rows(mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'")) == 1) ? true : false;
}
try this
function login($username, $password) {
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
$query = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'") ;
if (mysql_num_rows($query) > 0 ) {
$data = true ;
}else {
$data = false ;
}
return $data ;
}
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'