?
Solved

PHP Login Form Problem

Posted on 2011-10-04
13
Medium Priority
?
485 Views
Last Modified: 2013-12-12
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

0
Comment
Question by:rolandmy
  • 4
  • 2
  • 2
  • +4
12 Comments
 
LVL 84

Accepted Solution

by:
Dave Baldwin earned 75 total points
ID: 36914859
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
 
LVL 15

Assisted Solution

by:Insoftservice
Insoftservice earned 75 total points
ID: 36915896
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
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 36916075
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Assisted Solution

by:Duboux
Duboux earned 75 total points
ID: 36916209
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
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 75 total points
ID: 36918179
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
 
LVL 2

Author Comment

by:rolandmy
ID: 36921869
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36922269
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
 
LVL 3

Expert Comment

by:Duboux
ID: 36922643
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36923838
@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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36923863
@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
 
LVL 11

Assisted Solution

by:Ovid Burke
Ovid Burke earned 75 total points
ID: 36927620
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
 
LVL 2

Author Closing Comment

by:rolandmy
ID: 36929710
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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Containers like Docker and Rocket are getting more popular every day. In my conversations with customers, they consistently ask what containers are and how they can use them in their environment. If you’re as curious as most people, read on. . .
In this article, I’ll talk about multi-threaded slave statistics printed in MySQL error log file.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses
Course of the Month16 days, 9 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question