Page 1 of 2

[SOLVED] User authentication within a login page...

Posted: Tue Jun 29, 2004 7:38 pm
by dardsemail
Hi,

I'm working on creating a login page. I have the following code thus far:

Code: Select all

<?php
require_once('Connections/conn_my_db.php');

// *** Validate request to login to this site.
session_start();

function authenticateUser($frm_username,$frm_password)
{
	
		$hostname = 'localhost'; 
		$username ='myname'; 
		$password ='mypwd123'; 
		$dbName = 'my_db'; 

		MYSQL_CONNECT($hostname, $username, $password) OR DIE("Unable to connect"); 
		@MYSQL_SELECT_DB("$dbName") OR DIE("Unable to select database");
		
	//Test the username and password parameters
	if (!isset($frm_username)||!isset($frm_password))
		return false;
		
	//Get the two character salt from the username collected
	$salt = substr($frm_username,0,2);
	
	//Encrypt the password
	$crypted_password=crypt($frm_password,$salt);
	
	//Formulate SQL and find user
	$query="SELECT password FROM users WHERE username='$frm_username' AND password='$crypted_password'";
	
	//execute the query
	$result = @mysql_query($query) or DIE(mysql_error());
	echo ($result);
	$count = mysql_num_rows($result);
	echo ($count);
	
	//exactly one row - then we have found the user
	if ($count==1)
	{
		header("Location:login.php");
	}
	else 
	{
		header("Location:orders.php");
	}
}

?>
I also have the form action set to:

Code: Select all

<?php
authenticateUser($frm_username,$frm_password);

?>
My problem is that when I run the application, I am sent back to my login page again and not to either of my desired outcomes...

Any help would be greatly appreciated.

Posted: Tue Jun 29, 2004 7:50 pm
by feyd

Code: Select all

$result = @mysql_query($query) or DIE(mysql_error()); 
   echo ($result); 
   $count = mysql_num_rows($result); 
   echo ($count); 
    
   //exactly one row - then we have found the user 
   if ($count==1) 
   { 
      header("Location:login.php"); 
   } 
   else 
   { 
      header("Location:orders.php"); 
   }
lemme get that straight.. if you found the correct user, you want to send them to login.php? :?

Posted: Tue Jun 29, 2004 8:39 pm
by dardsemail
OOPs - I got it backward, but even when I changed it I received the same results - I just go back to the login page.

Very odd...

Posted: Tue Jun 29, 2004 11:23 pm
by markl999
echo $query; and see if it 'looks' ok. If it does then run the query in a mysql prompt (or phpMyAdmin / whatever) and see if it returns results ok. Zero or more than 1 result would explain your problem.

Possible another problem

Posted: Tue Jun 29, 2004 11:56 pm
by EricS
I don't see you doing any validation on the input, other than isset(), before querying the database. I'm hoping that is somewhere else in your code and just not shown here.

Taking ANY input from the user for granted is a SERIOUS NO NO. Take a look into cross-site scripting and sql injections for things that can and will become problems for you.

Not trying to flame you or be a prick, just trying to same you a lot of heartache and agony in the future.

Hope this helps,

Posted: Wed Jun 30, 2004 10:52 am
by dardsemail
ok - now i'm really f*(&ed up...

I tried to echo my query and wasn't getting the correct query in return. I've changed some stuff around - and now I'm really messed up.

Here's what my code looks like now:

Code: Select all

<?php
// *** Validate request to login to this site.
session_start();

function authenticateUser($frm_username,$frm_password)
{
		$hostname = 'localhost'; 
		$username ='myname'; 
		$password ='mypwd123'; 
		$dbName = 'my_db'; 

	//Get the two character salt from the username collected
	$salt = substr($frm_username,0,2);
	echo ("salt ='$salt'");
	
	//Encrypt the password
	$crypted_password=crypt($frm_password,$salt);
	echo
	//Formulate SQL and find user
	$query="SELECT password FROM users WHERE username='$frm_username' AND password='$crypted_password'";
	
	MYSQL_CONNECT($hostname, $username, $password) OR DIE("Unable to connect"); 
	@MYSQL_SELECT_DB("$dbName") OR DIE("Unable to select database");
	
	//execute the query
	$result = @mysql_query($query) or DIE(mysql_error());
	$count = mysql_num_rows($result);

	//exactly one row - then we have found the user
	if (mysql_num_rows($result)==1)
	{
		//Register the frm_username to show the user is logged in
		session_register("frm_username");
		
		//Clear any other session variables
		if (session_is_registered("errors"))
		//Deleter the form errors session variable
		session_unregister("errors");
		
		//Redirect to a calling page?
		if(session_is_registered("referer"))
		{
			//Delete the referer session variable
			session_unregister("referer");
			
			//Then use it to redirect
			header("Location:$referer");
			exit;
		}
		else 
		{
			header("Location:orders.php");
			exit;
		}}
		else
		{
			//Ensure the username is not registered, so the user is not logged in
			if (session_is_registered("frm_username"))
				session_unregister("frm_username");
				
			//Register an error message
			session_register("message");
			$message="Username or password incorrect.".
			"login failed.";
			
			//Show the login page
			login_page();
			exit;
		}
}

function login_page()
{
?>
<html>
<body>
<form ACTION="<?php authenticateUser($frm_username, $frm_password);?>" method="POST">
<table align="center" width="75%"  border="0" cellspacing="0" cellpadding="0">
	   <tr>
	   	 <td>User Name</td>
               <td><input type="text" name="frm_username" /></td>
          </tr>
          <tr>
                 <td>Password</td>
                 <td><input type="password" name="frm_password" />
          </td>
          </tr>
          </table><br />
		<input name="submit" type="submit" value="Submit" />
	         </form>
</body>
</html>
<?php
}
?>
Right now, when I call this page I get a blank screen! Help!

Re:
Taking ANY input from the user for granted is a SERIOUS NO NO. Take a look into cross-site scripting and sql injections for things that can and will become problems for you.
I have a nice little script I found for cleaning the data, but I'm not sure how to implement it - here it is:

Code: Select all

<?php
function clean($input, $maxLength)
{
  $input = substr($input, 0, $maxLength);
  $input = EscapeShellCmd($input);
  return = ($input);
}

?>
I can't figure out how to run the variables through it.

Posted: Wed Jun 30, 2004 11:00 am
by lostboy
why not just md5 the password with javascript? then submit the form...instant encryption and the password is never transmitted in the clear. Other than that, you can't call the login function that way...

As for the clean function, its better for you to write your own that matches your needs. Regex is the way to go here. You should write a simple regex to ensure that both fields meet your requirements for your input (like length, whether you allow only alpha characters, alphanumerics or all symbols)...

Code: Select all

<?php 
// *** Validate request to login to this site. 
session_start(); 

if ($_POST['submit']){
   $frm_username = @$_POST['frm_username'];
   $frm_password  = @$_POST['frm_password'];
   
  authenticateUser($frm_username,$frm_password);
}else{
   login_page(); 

}//end if

function authenticateUser($frm_username,$frm_password) 
{ 
      $hostname = 'localhost'; 
      $username ='myname'; 
      $password ='mypwd123'; 
      $dbName = 'my_db'; 

   //Get the two character salt from the username collected 
   $salt = substr($frm_username,0,2); 
   echo ("salt ='$salt'"); 
    
   //Encrypt the password 
   $crypted_password=crypt($frm_password,$salt); 
   echo 
   //Formulate SQL and find user 
   $query="SELECT password FROM users WHERE username='$frm_username' AND password='$crypted_password'"; 
    
   MYSQL_CONNECT($hostname, $username, $password) OR DIE("Unable to connect"); 
   @MYSQL_SELECT_DB("$dbName") OR DIE("Unable to select database"); 
    
   //execute the query 
   $result = @mysql_query($query) or DIE(mysql_error()); 
   $count = mysql_num_rows($result); 

   //exactly one row - then we have found the user 
   if (mysql_num_rows($result)==1) 
   { 
      //Register the frm_username to show the user is logged in 
      session_register("frm_username"); 
       
      //Clear any other session variables 
      if (session_is_registered("errors")) 
      //Deleter the form errors session variable 
      session_unregister("errors"); 
       
      //Redirect to a calling page? 
      if(session_is_registered("referer")) 
      { 
         //Delete the referer session variable 
         session_unregister("referer"); 
          
         //Then use it to redirect 
         header("Location:$referer"); 
         exit; 
      } 
      else 
      { 
         header("Location:orders.php"); 
         exit; 
      }} 
      else 
      { 
         //Ensure the username is not registered, so the user is not logged in 
         if (session_is_registered("frm_username")) 
            session_unregister("frm_username"); 
             
         //Register an error message 
         session_register("message"); 
         $message="Username or password incorrect.". 
         "login failed."; 
          
         //Show the login page 
         login_page(); 
         exit; 
      } 
} 

function login_page() 
{ 
?> 
<html> 
<body> 
<form ACTION="<?=$_SERVER['PHP_SELF'];?>" method="POST"> 
<table align="center" width="75%"  border="0" cellspacing="0" cellpadding="0"> 
      <tr> 
          <td>User Name</td> 
               <td><input type="text" name="frm_username" /></td> 
          </tr> 
          <tr> 
                 <td>Password</td> 
                 <td><input type="password" name="frm_password" /> 
          </td> 
          </tr> 
          </table><br /> 
      <input name="submit" type="submit" value="Submit" /> 
            </form> 
</body> 
</html> 
<?php 
} 
?>
edit: fix to form action element

Posted: Wed Jun 30, 2004 11:05 am
by dardsemail
I'll try the md5 encryption.. do i then need to unencrypt when i call from the db during the authentication?

How can I call the login function?

Posted: Wed Jun 30, 2004 11:06 am
by Joe
MD5 is a hash not an encryption. Keep that in mind. It will be very useful to you! ;)

Joe 8)

Posted: Wed Jun 30, 2004 11:09 am
by lostboy
dardsemail wrote:I'll try the md5 encryption.. do i then need to unencrypt when i call from the db during the authentication?

How can I call the login function?
No. the encryption is one way, you simply compare the md5 from the form to the users password created on registration, since md5 should return the same value whether its generated by php, javascript or asp.

Sorry, was making changes in the code even as you were reading it.

Posted: Wed Jun 30, 2004 2:42 pm
by dardsemail
I changed my registration form so that it uses the MD5 hash - here is the section associated with that:

Code: Select all

<?php
		$username=$_POST["frm_username"];
		$password=$_POST["frm_password"];
		
		//Use the first two characters of the username as salt
		//$salt = substr($username,0,2);
		
		//Create the encrypted password
		$stored_password = md5($password);
				
//Create a query to insert the customer
@mysql_query("INSERT INTO users(firstName, lastName, username,password) VALUES('".$_POST['frm_firstName']."', '".$_POST['frm_lastName']."','".$_POST['frm_username']."','$stored_password')") OR DIE(mysql_error());

//Now show the registration successful page
header("Location:registrationsuccessful.php");

?>
that seems to work fine.

then i changed the login so that it looks for the hashed password as such:

Code: Select all

<?php
	//Encrypt the password
	$crypted_password=md5($frm_password);
	echo
	//Formulate SQL and find user
	$query="SELECT password FROM users WHERE username='$frm_username' AND password='$crypted_password'";
	
	MYSQL_CONNECT($hostname, $username, $password) OR DIE("Unable to connect"); 
	@MYSQL_SELECT_DB("$dbName") OR DIE("Unable to select database");
	
	//execute the query
	$result = @mysql_query($query) or DIE(mysql_error());
	$count = mysql_num_rows($result);
...

?>
The registration works fine and I now show an accurate SQL string of the following when I try to login:

Code: Select all

SELECT password FROM users WHERE username='visitor2' AND password='d41d8cd98f00b204e9800998ecf8427e'
When I check the database, the password that appears in the database is:

e99a18c428cb

Of course, I'm getting 0 rows returned. What's happening here?

Finally, I'm not familiar with writing a regex. Is there a good tutorial on that somewhere?

Posted: Wed Jun 30, 2004 3:04 pm
by EricS
What is the length you specified for the password field in the database. If its too few characters, it will chop any data you try to save or select from it.

Hope this helps.

Posted: Wed Jun 30, 2004 3:13 pm
by dardsemail
Ok. I got the password hashing working, but now I'm getting some odd results. It seems that I'm going to the following URL:

I'm getting somewhere just not where I want to go. What I'd like to do is have this script prompted when non-logged in users try to access restricted pages. Upon successful login, they should be taken to the page that they were trying to access. If they are already logged in, then they should be given access to the appropriate page. I hope that makes sense.

I'm trying to determine how I would do this given the above noted code.

Thanks!!!

Posted: Fri Jul 02, 2004 10:13 am
by lostboy
the accesscheck variable in the url, does it have spaces?it might explain the extra symbols...I tend to use a one word descriptor for the page. Another option is to get the http_referer as the callback page...

as to your question, try urldecode(accesscheck) to get the page name...

Posted: Fri Jul 02, 2004 10:50 am
by feyd
%2F = /