PHP Login Form Problem

In the attached code, I keep getting the same result, its as if not reading the db..

Wrong Username or Password. Please retry. <-- always. Help?
<?php
//define(DOC_ROOT,dirname(__FILE__)); // To properly get the config.php file
$username = $_POST['username']; //Set UserName
$password = $_POST['password']; //Set Password
$msg ='';
if(isset($username, $password)) {
//if(isset($username)) {
    ob_start();
    //include('config.php'); //Initiate the MySQL connection
	require_once('config.php');
    // To protect MySQL injection (more detail about MySQL injection)
    $myusername = stripslashes($username);
    //$mypassword = stripslashes($password);
    $myusername = mysqli_real_escape_string($dbC, $username);
    //$mypassword = mysqli_real_escape_string($dbC, $mypassword);
    //$sql="SELECT * FROM client WHERE username='$myusername' and password=SHA('$mypassword')";
	$sql="SELECT * FROM client WHERE username='$myusername'";
    $result=mysqli_query($dbC, $sql);
    // Mysql_num_row is counting table row
    $count=mysqli_num_rows($result);
    // If result matched $myusername and $mypassword, table row must be 1 row
    if($count==1){
		$msg = "wee";
		header("location:xlogin.php?msg=$msg");
        // Register $myusername, $mypassword and redirect to file "admin.php"
        //session_register("admin");
        //session_register("password");
        //$_SESSION['name']= $myusername;
        //header("location:xadmin.php");
    }
    else {
//		echo $username;
        $msg = "Wrong Username or Password. Please retry";
		//$msg = $myusername;
        header("location:xlogin.php?msg=$msg");
    }
    ob_end_flush();
}
else {
    header("location:xlogin.php?msg=Please enter some username and password");
}
?>

Open in new window

LVL 2
rolandmyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
Please click on "Request Attention" and get your question zones changed to MySQL and PHP.  SQL Server 2005 is not being used in your page.

Are you using mysqli_real_escape_string($dbC, $username); to INSERT the user name in the first place?  Unless you're allowing punctuation in your username and password, it is probably not needed. http://us.php.net/manual/en/mysqli.real-escape-string.php
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
InsoftserviceCommented:
You had provided the username and password i  single quotes. please change and echo the o/p of $sql
and check in mysql gui tool.
echo $sql="SELECT * FROM client WHERE username='".$myusername."' AND password = SHA('".$mypassword."')";


0
Guy Hengel [angelIII / a3]Billing EngineerCommented:
please try to quote the password column name:
echo $sql="SELECT * FROM client WHERE username='".$myusername."' AND `password` = SHA('".$mypassword."')";

Open in new window

0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

DubouxCommented:
Doesn't mysqli_real_escape_string() already do the stripslashes() part ?

Also, I see u only check on the username part atm, so let's have that work first.
You code doesn't show any errors, so perhaps it's handy to do that first:

CHange:
$result=mysqli_query($dbC, $sql);

into:
$result=mysqli_query($dbC, $sql) or die (mysqli_error());

ps, I'm not at home with MySql lite, so I'm just guessing the function mysqli_error() exists...
if not, try mysql_error();
0
Ray PaseurCommented:
I doubt if I can debug your code, but I can show you an article with tested and working code examples that teaches the design patterns used in PHP client authentication.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

HTH, ~Ray
0
rolandmyAuthor Commented:
Ok I followed Ray's advice but I always get "grrr" as result. Doesn't seem to be connecting to the DB.

My config.php is as below while my login.php is in the attached code snippet:
<?php // RAY_EE_config.php

// WHEN WE ARE DEBUGGING OUR CODE, WE WANT TO SEE ALL THE ERRORS!
error_reporting(E_ALL);

// REQUIRED FOR PHP 5.1+
date_default_timezone_set('Asia/Singapore');

// THE LIFE OF THE "REMEMBER ME" COOKIE
//define('REMEMBER', 60*60*24*7); // ONE WEEK IN SECONDS

// WE WANT TO START THE SESSION ON EVERY PAGE
session_start();

// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "xxx.xx.xxx.xx:xxxxx"; // PROBABLY THIS IS OK
$db_name = "xxx";        // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "xxxxx";
$db_word = "xxxxx";

// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $errmsg <br/>";
    die("NO DATA BASE $db_name");
}

// DEFINE THE ACCESS CONTROL FUNCTION
function access_control($test=FALSE)
{
    // REMEMBER HOW WE GOT HERE
    $_SESSION["entry_uri"] = $_SERVER["REQUEST_URI"];

    // IF THE UID IS SET, WE ARE LOGGED IN
    if (isset($_SESSION["uid"])) return $_SESSION["uid"];

    // IF WE ARE NOT LOGGED IN - RESPOND TO THE TEST REQUEST
    if ($test) return FALSE;

    // IF THIS IS NOT A TEST, REDIRECT TO CALL FOR A LOGIN
    header("Location: xlogin.php");
    exit;
}

// DEFINE THE "REMEMBER ME" COOKIE FUNCTION
//function remember_me($uuk)
//{
    // CONSTRUCT A "REMEMBER ME" COOKIE WITH THE UNIQUE USER KEY
//    $cookie_name    = 'uuk';
//    $cookie_value   = $uuk;
//    $cookie_expires = time() + date('Z') + REMEMBER;
//    $cookie_path    = '/';
//    $cookie_domain  = NULL;
//    $cookie_secure  = FALSE;
//    $cookie_http    = TRUE; // HIDE COOKIE FROM JAVASCRIPT (PHP 5.2+)

    // SEE http://us3.php.net/manual/en/function.setcookie.php
//    setcookie
 //   ( $cookie_name
//    , $cookie_value
 //   , $cookie_expires
 //   , $cookie_path
 //   , $cookie_domain
 //   , $cookie_secure
 //   , $cookie_http
//    )
//    ;
//}



// DETERMINE IF THE CLIENT IS ALREADY LOGGED IN BECAUSE OF THE SESSION ARRAY
//if (!isset($_SESSION["uid"]))
//{

    // DETERMINE IF THE CLIENT IS ALREADY LOGGED IN BECAUSE OF "REMEMBER ME" FEATURE
 //   if (isset($_COOKIE["uuk"]))
//    {
//        $uuk = mysql_real_escape_string($_COOKIE["uuk"]);
//        $sql = "SELECT uid FROM client WHERE uuk = '$uuk' LIMIT 1";
//        $res = mysql_query($sql);

        // IF THE QUERY SUCCEEDED
//        if ($res)
 //       {
            // THERE SHOULD BE ONE ROW
//            $num = mysql_num_rows($res);
//            if ($num)
 //           {
                // RETRIEVE THE ROW FROM THE QUERY RESULTS SET
//                $row = mysql_fetch_assoc($res);

                // STORE THE USER-ID IN THE SESSION ARRAY
//                $_SESSION["uid"] = $row["uid"];

                // EXTEND THE "REMEMBER ME" COOKIE
//                remember_me($uuk);
//            }
//        }
//    }
//}

P.s. Sorry for late reply, I live on a +8 GMT timezone.

<?php // RAY_EE_login.php
require_once('config.php');

// WAS EVERYTHING WE NEED POSTED TO THIS SCRIPT?
if ( (!empty($_POST["uid"])) && (!empty($_POST["pwd"])) )
{
    // YES, WE HAVE THE POSTED DATA. ESCAPE IT FOR USE IN A QUERY
    $uid = mysql_real_escape_string($_POST["uid"]);
    $pwd = mysql_real_escape_string($_POST["pwd"]);

    // CONSTRUCT AND EXECUTE THE QUERY - COUNT THE NUMBER OF ROWS RETURNED
    //$sql = "SELECT username FROM client WHERE username = '$uid' AND password = '$pwd' LIMIT 1";
	$sql = "SELECT username FROM client WHERE username = '$uid' LIMIT 1";
    $res = mysql_query($sql);

    // IF THE QUERY FAILED, GIVE UP
    if (!$res) die( mysql_error() );

    // THERE SHOULD BE ONE ROW IF THE VALIDATION WAS PROCESSED SUCCESSFULLY
    $num = mysql_num_rows($res);
    if ($num)
    {
        // RETRIEVE THE ROW FROM THE QUERY RESULTS SET
        $row = mysql_fetch_assoc($res);

        // STORE THE USER-ID IN THE SESSION ARRAY
        $_SESSION["uid"] = $row["username"];

        // IS THE "REMEMBER ME" CHECKBOX SET?
        //if (isset($_POST["rme"]))
        //{
        //    remember_me($row["uuk"]);
        //}

        // REDIRECT TO THE ENTRY PAGE OR TO THE HOME PAGE
        if (isset($_SESSION["entry_uri"]))
        {
            //header("Location: {$_SESSION["entry_uri"]}");
			//header("Location: index.php");
			echo "yes!";
            exit;
        }
        else
        {
            //header("Location: /");
			echo "grrr";
			//header("Location: index-add.php");
            exit;
        }
    } // END OF SUCCESSFUL VALIDATION
    else
    {
        echo "SORRY, VALIDATION FAILED USING $uid AND $pwd \n";
    }
} // END OF FORM PROCESSING - PUT UP THE LOGIN FORM
?>
<form method="post">
PLEASE LOG IN
<br/>UID: <input name="uid" type="text" />
<br/>PWD: <input name="pwd" type="password" />
<!--<br/><input type="checkbox" name="rme" />KEEP ME LOGGED IN (DO NOT CHECK THIS ON A PUBLIC COMPUTER)-->
<br/><input type="submit" value="LOGIN" />
</form>

Open in new window

0
Ray PaseurCommented:
I do not recall having an error message that said "grr."  For better or worse, computer programming is a fairly precise science.  Please show us the code you are actually using, line for line, and show us the messages you are actually receiving, thanks.
0
DubouxCommented:
That "Grrr" has nothing to do with database connection.

It's mad because you dind't define $_SESSION["entry_uri"]

If you want to know if the creation of the session has successfully worked, after a successful login, then check for: $_SESSION["uid"] instead of $_SESSION["entry_uri"].


ps, I ain't too fond of just using "if ($num)".
0
Ray PaseurCommented:
@Duboux: regarding this: Doesn't mysqli_real_escape_string() already do the stripslashes() part ? Nope.  If there are escape slashes in the query string, it will still escape the characters described on the man page.  The combination of magic_quotes and programmatic escape often leads to the presence of escape characters in the data base.  Here is the description of the escape function().
http://php.net/manual/en/mysqli.real-escape-string.php

Here is an article that explains why magic_quotes is not your friend.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_6630-Magic-Quotes-a-bad-idea-from-day-one.html

Regarding just using "if ($num)". Here is a link to the man page for the PHP if() statement.  
http://php.net/manual/en/control-structures.if.php

In PHP, the if() statement evaluates expressions, and in this case the expression is the value of $num.  Here is a link to the documentation about expressions.
http://php.net/manual/en/language.expressions.php

Here is a link to the page that describes some of the comparison operators.
http://us2.php.net/operators.comparison

So an if() statement that contains an expression with a resolved value of zero, NULL or FALSE will be evaluated FALSE and the resulting control structure will not be executed.

It looks to me like our author may be confused by the changes to the indentation and the comments in the code.  I find it very difficult to get programming right when I do not give care and attention to the correct indentation of the control structures.  And commenting out some code but leaving it in the script can be a recipe for confusion.  In my own work I like to use a modified Zend coding standard.  It calls for indentation of four characters with each level of control.
0
Ray PaseurCommented:
@rolandmy: regarding this: Doesn't seem to be connecting to the DB.  If you're using the config script I posted in the article, you will see that the script will die on line 37 with a diagnostic message if either the data base connect() or select() function fails.  So that is not the problem, for sure.  I think that some of your changes to the login script have removed some essential parts of the logic.  If you can describe in plain, non-technical language why you made those changes and what you are trying to achieve I may be able to help you get it right.

I think you might enjoy this book.  It will not make you a pro, but it will definitely help you get a foundation in PHP and MySQL.  It is very readable and has great examples.  Now in its fourth printing, it has been a part of my professional library since Edition One.
http://www.sitepoint.com/books/phpmysql4/
0
Ovid BurkeConsultant InstructorCommented:
My take:
<?php
/*
madaboutasp_EE.php
*/


session_start();

if( isset( $_POST['submit'] ) && $_POST['submit'] == "Login" )
{
	// get rid of the submit button
	unset( $_POST['submit'] );
	
	// call ur db connection here
	require_once ( 'config.php' );
	
	// create an empty array to hold possible errors
	$errors = array();
	
	// basic validation of username
	if( empty( $_POST['username'] ) || is_array( $_POST['username'] ) || $_POST['username'] == "" ) 
	{
		$errors['username'] = "Please enter a valid username.";	
	} 
	else 
	{
		$username = mysqli_real_escape_string( $dbC, $_POST['username'] );	
	}
	
	// basic validation of password
	if( empty( $_POST['password']) || is_array( $_POST['password'] ) || $_POST['password'] == "" ) 
	{
		$errors['password'] = "Please enter a valid password.";	
	} 
	else 
	{
		$password = mysqli_real_escape_string( $dbC, $_POST['password'] );	
	}
	
	if( empty( $errors ) ) 
	{ // continue if no errors
		
		/*
		At this stage, the manner in which you query the database depends on how specific you choose to be in case of errors. Do you query $username and $password at once or $username only, and match the $password later? My preference is to lookup the username and match the password later. This way I can specify precisely which credential is eroneous. Here we go then:
		*/
		
		$sql = mysqli_query( $db_conn, "SELECT * FROM client WHERE username = '{$username}' LIMIT 1" );
		if( mysqli_num_rows( $sql ) === 0 ) 
		{
			$errors['username'] = "The username, '{$username}' is not in our database.";	
		} 
		else 
		{
			$row = mysqli_fetch_array( $sql, MYSQLI_ASSOC );
			if( sha1($password) !== $row['password'] ) 
			{
				$errors['password'] = "Incorrect password!";
			} 
			else 
			{
				// create or set session data
				$_SERVER['user'] = $row['clientid']; // or whatever column name you use
				$_SERVER['name'] = $username;
				
				// redirect to success page
				header( "Location: xadmin.php" );
				exit;
			}
		}
	}
}

/* UNCOMMENT TO TEST -->

if( !empty( $errors ) ) {
	foreach( $errors as $key => $error) {
		echo "- {$error}\n";
	}
}

*/

?>

Open in new window

0
rolandmyAuthor Commented:
Dear Experts, it was my bad. As the password is encrypted in the database, I thought I was having problems with my login script. Apparently I changed until I was confused. I just needed this in my original login:

$query="SELECT * FROM client WHERE username='$login' AND password='".md5($_POST['password'])."'";

Going to distribute the points, thanks for the help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.