PHP problem - unknown problem.

+2 Jad Samadi · December 23, 2014
So hey there guys i want to start first by thinking you for helping me in the previous problems i had and well yet i have a new one today .
As i was working on my login/Register system i actually was surprised to realize something new in PHP .... or maybe its just my fault .
Any way let me show you what is happening .
This is my code : 


<?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 and a password';


          } else if(user_exists($username) === false) {


            $errors[] = 'We can\'t find that username. Have you registered ?';


          }else if (user_active() === false) {


            $errors[] = 'You haven\'t activated your account';


          } else { 


           //here


          }











print_r($errors);


}


?>



i don't suppose any thing is wrong in there yet when you test it you will notice that one of the 'else if' statements don't actually work . ... its like the file is only reading the first one.
Ill explain more . I opened my index page and tried to login with empty username and password boxes . It gives me this error :
Array ( [0] => You need to enter a username and a password )
witch is great ... that means it works !
Now i tried to test if the 'user_exists' function work . So i entered a username and password that isn't saved in my database and i got that error :
Array ( [0] => We can't find that username. Have you registered ? )
Works great ! Now the problem .... When i try to test the 'user_active' function it doesn't work ... I enter the username and password that is saved in my database with the active state equal to 0 where i should then get the error :
You haven\'t activated your account
But instead i get this error :
Array ( [0] => We can't find that username. Have you registered ? )
Now i know i probably made a mistake in the function so it does not work but no i didn't.
I tried to switch the active function and the exists one and my code became :


<?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 and a password';


          }else if (user_active() === false) {


            $errors[] = 'You haven\'t activated your account';


          } else if(user_exists($username) === false) {


            $errors[] = 'We can\'t find that username. Have you registered ?';


          } else { 


           //here


          }











print_r($errors);


}


?>



And for some reason now i cant get this error :
Array ( [0] => We can't find that username. Have you registered ? )
instead i get this one :
Array ( [0] => You haven't activated your account )
So ye ... for both cases if i enter a correct or incorrect username/password.
I don't think i can explain more and i think this code would help as well(the functions) :


<?php





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;


}





?>




So if you can help me i would really appreciate it .Thanks for reading

Post a Reply

Replies

- page 2
Oldest  Newest  Rating
0 Ron Butcher · December 26, 2014
If your query fails it is the cause of your problems.  

In your user_exists function, you run the query that counts the number of users with the specific id and if the active field is 1.  If the query finds a match (like it should on a valid login) it returns true, otherwise it returns false.  So when the query runs and fails, it is equal to an error rather than 1 like it is supposed to.  Your statement therefore returns false and that is what your else if statement is looking for to execute its code.  The page will then populate the $errors array and exit the if else statements since it is only looking for one of those to be true.

The other thing is you need to make sure that you are checking to see if the user exists before checking to see if it is active.  I would use nested if statements instead of the else if statements.

I know that this is how the tutorials log in users, but to be honest I am not a huge fan of this style, but that is just me.  Here is how I do it in a nutshell:


<?php
$errors = '';

if(!empty($_POST))
{
$username = sanitize($_POST['username']);
$password = sanitize($_POST['password']);

if(!empty($username) || !empty($password))
{
$qry = "SELECT `id`, `username`, `password`, `active` FROM `users` WHERE `username` = '$username'";  //  Pull necessary information from the database about the user
$result = $mysqli->query($qry) //  I prefer the OOP method of mysqli, it is just a personal preference.

if($result->num_rows != 1)   // Check to make sure that only one result is present
{
$errors = 'Username or Password is Incorrect';  //  I don't tell the user which part they entered incorrectly to discourage hackers.
}
else
{
$userData = $result->fetch_object();   //  Gather all the users information to finish comparing
//  Right here is where I would normally hash and add salt to the $password variable to prepare it to compare to my database.
if($password != $userData->password)   //  Check to see if the password is correct
{
$errors = 'Username or Password is Incorrect';
}
else if(!$userData->active)  //  Check to see if the user is active or not
{
$errors = 'This Account is No Longer Active.  Please Contact the Site Administrator';
}
else
{
$login_user($userData);
}
}
}
else  //  This statement only runs if one of the fields was left blank.
{
$errors = 'Please Enter Both A User Name and Password';
}
}



It is a little more code, but using the nested if statements allow me a lot more control over the situation.  It allows me to run the database query only one time and use those results for the rest of the page.  That makes the page a bit quicker, especially if I have a huge database.

I can also check to see if the user is supposed to change their password, or if there is another specific alert they are supposed to get upon login.

I can also use this setup to log bad username attempts, or bad password attempts.  I can lock the user account after so many bad attempts, and the log allows me to watch for hackers using dictionary or similar attacks on my site.
0 Jad Samadi · December 26, 2014
alright thanks for your reply but after testing your code :

<?php
include 'core/init.php';

$errors = '';

if(!empty($_POST))
{
$username = sanitize($_POST['username']);
$password = sanitize($_POST['password']);

if(!empty($username) || !empty($password))
{
$qry = "SELECT `id`, `username`, `password`, `active` FROM `users` WHERE `username` = '$username'";
$result = $mysqli->query($qry)

if($result->num_rows != 1)
{
$errors = 'Username or Password is Incorrect';
}
else
{
$userData = $result->fetch_object();

if($password != $userData->password)
{
$errors = 'Username or Password is Incorrect';
}
else if(!$userData->active)
{
$errors = 'This Account is No Longer Active.  Please Contact the Site Administrator';
}
else
{
$login_user($userData);
}
}
}
else
{
$errors = 'Please Enter Both A User Name and Password';
}
}
          
          print_r($errors); 
}

?>

And after testing i got this error : ( ! ) Parse error: syntax error, unexpected 'if' (T_IF) in C:\wamp\www\lr\login.php on line 14
And then after going back to the code i found the 'if' on this line :

if($result->num_rows != 1)

And i tried to fix it but  i didn't find a thing .
Please help ?
0 Ron Butcher · December 26, 2014
Sorry, I missed the semicolon on the line above (line 12).  It should be 

$result = $mysqli->query($qry); // <-Missing ;

if($result->num_rows != 1)
//....... Rest of code
0 Jad Samadi · December 27, 2014
Alright sorry if im being annoying or any thing .
Thanks  for your reply and after testing the code :


<?php

include 'core/init.php';
ini_set('display_errors', FALSE);

$errors = '';

if(!empty($_POST))
{
$username = sanitize($_POST['username']);
$password = sanitize($_POST['password']);

if(!empty($username) || !empty($password))
{
$qry = "SELECT `id`, `username`, `password`, `active` FROM `users` WHERE `username` = '$username'";
$result = $mysqli->query($qry);

if($result->num_rows != 1)
{
$errors = 'Username or Password is Incorrect';
}
else
{
$userData = $result->fetch_object();

if($password != $userData->password)
{
$errors = 'Username or Password is Incorrect';
}
else if(!$userData->active)
{
$errors = 'This Account is No Longer Active.  Please Contact the Site Administrator';
}
else
{
$login_user($userData);
}
}
}
else
{
$errors = 'Please Enter Both A User Name and Password';
}



                  print_r($errors);
        }

          

?>


This part works :

$errors = 'Please Enter Both A User Name and Password';

Yet this whole part don't ;

$qry = "SELECT `id`, `username`, `password`, `active` FROM `users` WHERE `username` = '$username'";
$result = $mysqli->query($qry);

if($result->num_rows != 1)
{
$errors = 'Username or Password is Incorrect';
}
else
{
$userData = $result->fetch_object();

if($password != $userData->password)
{
$errors = 'Username or Password is Incorrect';
}
else if(!$userData->active)
{
$errors = 'This Account is No Longer Active.  Please Contact the Site Administrator';
}
else
{
$login_user($userData);
}
}
}

If i leave both the  username and password empty it give me the error :

Please Enter Both A User Name and Password

Witch is good but if i leave 1 empty it give me a blank page witch is bad for there were no errors
Im still really new to this language of PHP and to be honest im trying to understand your code and i did yet i don't get the problem.
So please help
Thanks for reading.
0 Ron Butcher · December 27, 2014
No problem, I didn't put any error checking into the database queries, so lets do that.  We also need to make sure that your database has the table layout we are looking for and that we are connecting properly.

This is how my database is setup, I have a database called 'test' with a table called 'users' that has the following information:

+---------+----------+----------+--------+
| user_id | username | password | active |
+---------+----------+----------+--------+
|       1 | ron      | ron      |      1 |
|       2 | dave     | dave     |      0 |
+---------+----------+----------+--------+

At the start of my page I include the database connect info and connect to the database like this:

<?php
// Define database connection variables
$host="localhost";
$dbUser="database_user";
$dbPass="database_password";
$dbName="database_nema";

// Connect to the database
$mysqli = new mysqli("$host", "$dbUser", "$dbPass", "$dbName");

// If there is a problem, kill the page and display the error
if($mysqli->connect_errno)
{
die(mysqli_connect_error());
}

I am pretty sure you defined the function sanitize, but that was not included in any of your code.  Here is how I wrote it:

//  Define the function sanitize
function sanitize($str)
{
global $mysqli; // Since we are calling a variable outside the function, we have to note it is a 'global' variable before using it
return $mysqli->real_escape_string($str);
}


Now I will go into the code, this is mostly what I put above, but with some error checking no my database query and a couple of clean up items as well.
	//  Initialize the error variable
$errors = '';

// See if the form has been submitted
if(!empty($_POST))
{
// Clean the information passed by the form
$username = sanitize($_POST['username']);
$password = sanitize($_POST['password']);

// Check to see if the username or password is empty (!) means false, so the statement basically says, if not empty......
if(!empty($username) || !empty($password))
{
$qry = "SELECT `user_id`, `username`, `password`, `active` FROM `users` WHERE `username` = '$username'"; // Pull necessary information from the database about the user
$result = $mysqli->query($qry) or die($mysqli->error); // I prefer the OOP method of mysqli, it is just a personal preference.

if($result->num_rows != 1) // Check to make sure that only one result is present
{
$errors = 'Username or Password is Incorrect'; // I don't tell the user which part they entered incorrectly to discourage hackers.
}
else
{
$userData = $result->fetch_object(); // Gather all the users information to finish comparing
// Right here is where I would normally hash and add salt to the $password variable to prepare it to compare to my database.
if($password != $userData->password) // Check to see if the password is correct
{
$errors = 'Username or Password is Incorrect';
}
else if(!$userData->active) // Check to see if the user is active or not
{
$errors = 'This Account is No Longer Active. Please Contact the Site Administrator';
}
else
{
echo 'Login Successful';
// Code to log in user goes here.
// $login_user($userData);
}
}
}
else // This statement only runs if one of the fields was left blank.
{
$errors = 'Please Enter Both A User Name and Password';
}
}

Give that a try.  Hopefully I left enough comments you can understand the process, if not let me know and I can explain further.  I did run this code through my setup before posting this time so you shouldn't get any errors as long as your database is setup properly.
0 Jad Samadi · December 28, 2014
Hey thanks for the code now i did not get any errors witch is  super cool BUT
this whole code now : 

<?php



//  Define database connection variables
        $host="localhost";
$dbUser="root";
$dbPass="";
$dbName="lr";

//  Connect to the database
$mysqli = new mysqli("$host", "$dbUser", "$dbPass", "$dbName");

//  If there is a problem, kill the page and display the error
if($mysqli->connect_errno)
{
die(mysqli_connect_error());
}

//  Define the function sanitize
function sanitize($str)
{
global $mysqli;  //  Since we are calling a variable outside the function, we have to note it is a 'global' variable before using it
return $mysqli->real_escape_string($str);
}
//  Initialize the error variable
        $errors = '';

        //  See if the form has been submitted
if(!empty($_POST))
{
//  Clean the information passed by the form
                $username = sanitize($_POST['username']);
$password = sanitize($_POST['password']);

                //  Check to see if the username or password is empty (!) means false, so the statement basically says, if not empty......
if(!empty($username) || !empty($password))
{
$qry = "SELECT `user_id`, `username`, `password`, `active` FROM `users` WHERE `username` = '$username'"; // Pull necessary information from the database about the user
$result = $mysqli->query($qry) or die($mysqli->error);  // I prefer the OOP method of mysqli, it is just a personal preference.

if($result->num_rows != 1) // Check to make sure that only one result is present
{
$errors = 'Username or Password is Incorrect'; // I don't tell the user which part they entered incorrectly to discourage hackers.
}
else
{
$userData = $result->fetch_object(); // Gather all the users information to finish comparing
// Right here is where I would normally hash and add salt to the $password variable to prepare it to compare to my database.
if($password != $userData->password) // Check to see if the password is correct
{
$errors = 'Username or Password is Incorrect';
}
else if(!$userData->active) // Check to see if the user is active or not
{
$errors = 'This Account is No Longer Active. Please Contact the Site Administrator';
}
else
{
echo 'Login Successful';
                                        //  Code to log in user goes here.
                                        //  $login_user($userData);
}
}
}
else // This statement only runs if one of the fields was left blank.
{
$errors = 'Please Enter Both A User Name and Password';
}
}



          

?>


Doesn't work at all and  as you i did edit the database connection info and tried to edit few stuff after posting this code here and yet nothing works ....
Sorry if im being annoying as i said before but i seriously can't understand this new Mysqli and OOP and mysqli thing ...
0 Jay Deshaun · December 28, 2014
MySQLi php functions and examples - http://www.w3schools.com/php/php_ref_mysqli.asp

Does the 'active' return a number or true/false?
0 Jad Samadi · December 28, 2014
i think it should return a true/false 
0 Jad Samadi · December 28, 2014
You know what ? your right .... i removed the active bullshit and i t worked finely .... Now its less complicated .
The active had a purpose to show registered users, i don't need that .
Thanks for your help hope you have a merry Christmas and a happy new year . You can close this thread. 
  • 1
  • 2

PHP

107,323 followers
About

Server-side, HTML embedded scripting language used to create dynamic Web pages.

Links
Moderators