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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

dardsemail
Forum Contributor
Posts: 136
Joined: Thu Jun 03, 2004 9:02 pm

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

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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? :?
dardsemail
Forum Contributor
Posts: 136
Joined: Thu Jun 03, 2004 9:02 pm

Post 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...
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post 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.
EricS
Forum Contributor
Posts: 183
Joined: Thu Jul 11, 2002 12:02 am
Location: Atlanta, Ga

Possible another problem

Post 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,
dardsemail
Forum Contributor
Posts: 136
Joined: Thu Jun 03, 2004 9:02 pm

Post 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.
lostboy
Forum Contributor
Posts: 329
Joined: Mon Dec 30, 2002 8:12 pm
Location: toronto,canada

Post 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
Last edited by lostboy on Wed Jun 30, 2004 11:16 am, edited 2 times in total.
dardsemail
Forum Contributor
Posts: 136
Joined: Thu Jun 03, 2004 9:02 pm

Post 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?
User avatar
Joe
Forum Regular
Posts: 939
Joined: Sun Feb 29, 2004 1:26 pm
Location: UK - Glasgow

Post by Joe »

MD5 is a hash not an encryption. Keep that in mind. It will be very useful to you! ;)

Joe 8)
lostboy
Forum Contributor
Posts: 329
Joined: Mon Dec 30, 2002 8:12 pm
Location: toronto,canada

Post 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.
dardsemail
Forum Contributor
Posts: 136
Joined: Thu Jun 03, 2004 9:02 pm

Post 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?
EricS
Forum Contributor
Posts: 183
Joined: Thu Jul 11, 2002 12:02 am
Location: Atlanta, Ga

Post 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.
dardsemail
Forum Contributor
Posts: 136
Joined: Thu Jun 03, 2004 9:02 pm

Post 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!!!
lostboy
Forum Contributor
Posts: 329
Joined: Mon Dec 30, 2002 8:12 pm
Location: toronto,canada

Post 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...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

%2F = /
Post Reply