Jump to content

PHP login/password auth. help!


sp00ks

Recommended Posts

Hey, Im new here and I have a small problem that I just can't wrap my head around.  Basically, I want it so that a user can log on with his username and password from SQL database. when he logs on he can see all the other usernames and passwords, and an option to delete them(if he has administrative rights) basically I'm still stuck on the first part, I can't get all the fields to appear, and my "Username or Password not found" always displays 4 times!

<?php
//1. Create a database connection
$connection = mysql_connect("localhost", "root", "****");
if(!$connection){
	die("Database connection failed: " . mysql_error());
}
//2. Select a database to use
$db_select = mysql_select_db("testing", $connection);
	if(!$db_select){
		die("Database failed: " . mysql_error());
	}
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
<style type="text/css" title="text/css" media="all">
.error {
font-weight: bold;
color: #C00
}
</style>

<title>Form Feedback</title>
</head>
<body>
<?php 
if ( empty($_POST['name']) || empty($_POST['password'])) {
echo '<p class="error">Please go back and fill out the form again.</p>';
}
?>


<?php
$name = $_POST['name'];
$pass = $_POST['password'];
	$q = ( "SELECT Username,Pwd,Admin FROM users");
	$result = mysql_query($q);
		if(!$q){
		die("Database query failed: " . mysql_error());
	}
	while ($row = mysql_fetch_array($result)) {

	//4. Use returned data
	if( $name == $row['Username'] && $pass == $row['Pwd']){
		echo '<table align="center" border = "1" cellspacing="1" cellpadding="1" width="20%"><tr><td align="center"><b>Name</b></td><td align="center"><b>Password</b></td></tr>';
		echo '<tr><td align="left">' . $row['Username'] . '</td><td align="left">'. $row['Pwd'] . '</td></tr> ';
		} else{
			echo"hey";
		}
}
?>
</table>


</body>
</html>

<?php
	//5. Close connection, Woudl've made it an include file, if I was not sending through email'
	if(isset($connection)){
		mysql_close($connection);
	}
	?>		

 

And my login screen

 

	<html>
	<title>Login</title>
	<body>
		<h1 align='center'>Please Log In</h1>
			<form method = "post" action = "handle_login.php">
				<table align='center' border = '1'>
				<tr>
				<th> Username </th>
				<td> <input type = "text" name = "name" /> </td>
				</tr>
				<tr>
				<th> Password </th>
				<td> <input type = "password" name = "password"/> </td>
				</tr>
				<tr>
				<td colspan ='2' align = 'center'>
				<input type = "submit" value = "Log In"/>
				</td>
				</tr>
				</table>
			</form>
	</body>
</html>

 

 

thank you!

Link to comment
Share on other sites

yeah, you shouldn't be selecting all the records, just the ones you need.

BUT MAKE SURE YOU ESCAPE YOUR DATA TO PREVENT SQL INJECTION!!!!

<?php
   //1. Create a database connection
   $connection = mysql_connect("localhost", "root", "****")
      or die("Database connection failed: " . mysql_error());
   //2. Select a database to use
   mysql_select_db("testing", $connection)
      or die("Database failed: " . mysql_error());
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
<style type="text/css" title="text/css" media="all">
.error {
font-weight: bold;
color: #C00
}
</style>

<title>Form Feedback</title>
</head>
<body>
<?php 
   if ( empty($_POST['name']) || empty($_POST['password'])) {
      echo '<p class="error">Please go back and fill out the form again.</p>';
   }else{
      $name = mysql_real_escape_string($_POST['name']); //VERY IMPORTANT
      $pass = mysql_real_escape_string($_POST['password']); //VERY IMPORTANT
      $q = sprintf("SELECT Username,Pwd,Admin FROM users WHERE Username = '%s' AND Pwd = '%s' LIMIT 1",$name,$pass);
      $result = mysql_query($q)
         or die("Database query failed: " . mysql_error());
      if($row = mysql_fetch_array($result)){ //Only need to select 1 row
         echo '<table align="center" border = "1" cellspacing="1" cellpadding="1" width="20%"><tr><td align="center"><b>Name</b></td><td align="center"><b>Password</b></td></tr>';
         echo '<tr><td align="left">' . $row['Username'] . '</td><td align="left">'. $row['Pwd'] . '</td></tr></table>';
      }else{
         echo '<p class="error">Invalid Username/Password.</p>';
      }
   }
?>
</body>
</html>

 

..you don't have to close DB connections, PHP will do that automatically

Link to comment
Share on other sites

BUT MAKE SURE YOU ESCAPE YOUR DATA TO PREVENT SQL INJECTION!!!!

 

This is important indeed, I saw this link the other day here on phpfreaks http://videos.code2design.com/ and was told to check the video of security, for a beginner like me I must say it was really useful and hopefully I spared myself of some trouble up ahead. Sorry if this has nothing really to do with your problem, but it is still important =)

Link to comment
Share on other sites

Thank you guys so much! you are really quick at replying.  I just wanted to know how would I display all the records? (each user name and password beside it all) I tried to remove limit 1 but it was unsuccessful  ???

 

I'm also trying to make it, if you are a admin, you can view the IsAdmin row(which displays, y or n)

 <?php if($row = mysql_fetch_array($result)){ //Only need to select 1 row
      
      		if($row['IsAdmin'] == 'y'){
         echo '<table align="center" border = "1" cellspacing="1" cellpadding="1" width="20%"><tr><td align="center"><b>Name</b></td><td align="center"><b>Password</b></td><td align="center"><b>Delete</b></td></tr>';
         echo '<tr><td align="left">' . $row['Username'] . '</td><td align="left">'. $row['Pwd'] . '</td><td align="left">'. $row['IsAdmin'] .'</td></tr></table>';
         }
         else if($row['IsAdmin'] == 'n'){
         	   echo '<table align="center" border = "1" cellspacing="1" cellpadding="1" width="20%"><tr><td align="center"><b>Name</b></td><td align="center"><b>Password</b></td></tr>';
         echo '<tr><td align="left">' . $row['Username'] . '</td><td align="left">'. $row['Pwd'] . '</td></tr></table>';
      }else{
         echo '<p class="error">Invalid Username/Password.</p>';
         }
        }
?>

 

I'm pretty sure i have my curly brackets messed up, but i can't seem to position them right

Link to comment
Share on other sites

<?php
   //1. Create a database connection
   $connection = mysql_connect("localhost", "root", "****")
      or die("Database connection failed: " . mysql_error());
   //2. Select a database to use
   mysql_select_db("testing", $connection)
      or die("Database failed: " . mysql_error());
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
<style type="text/css" title="text/css" media="all">
.error {
font-weight: bold;
color: #C00
}
</style>

<title>Form Feedback</title>
</head>
<body>
<?php 
   if ( empty($_POST['name']) || empty($_POST['password'])) {
      // Make sure they passed info
      echo '<p class="error">Please go back and fill out the form again.</p>';
   }else{
      // Authenticate the user
      $name = mysql_real_escape_string($_POST['name']); //VERY IMPORTANT
      $pass = mysql_real_escape_string($_POST['password']); //VERY IMPORTANT
      $q = sprintf("SELECT Username,Pwd,Admin FROM users WHERE Username = '%s' AND Pwd = '%s' LIMIT 1",$name,$pass);
      $result = mysql_query($q)
         or die("Database query failed");
      $user = mysql_fetch_array($result);
      if(!$user){
         echo '<p class="error">Invalid Username/Password.</p>';
      }else{
         //They are authenticated, let's do the loop
         $q = "SELECT Username,Pwd,Admin FROM users";
         $result = mysql_query($q)
            or die("Database query failed");
         // Start the table
         echo '<table align="center" border = "1" cellspacing="1" cellpadding="1" width="20%">';
         //Header
         echo '<tr><th align="center">Name</th><th align="center">Password</th>';
         if($user['IsAdmin'] == 'y'){
            echo '<th align="center">Is Admin</th>';
         }
         echo '</tr>';
         while($row = mysql_fetch_array($result)){
            echo '<tr><td align="left">' . $row['Username'] . '</td><td align="left">'. $row['Pwd'] . '</td>';
            if($user['IsAdmin'] == 'y'){
               echo '<td align="left">'. $row['IsAdmin'] .'</td>';
            }
            echo '</tr>';
         }
         echo '</table>';
      }
   }
?>
</body>
</html>

Link to comment
Share on other sites

thanks so much, I'm familiar with other languages but php seems to give me a  hard time.  Anyways, for the button, I basically just want it to delete the row, no need to redirect me to another page. so I assume its POST.

The delete will be right next to each row that my program creates. (I have five rows, so five delete buttons beside each one, when the corresponding row is delete, it just gets removed from mysql)

 

In the ($user['IsAdmin']) i can add just sql code? such as DELETE * FROM users WHERE (this is the hard part) *the delete button corresponds to the row* ??? so confusing, heh.

Link to comment
Share on other sites

We need to have a talk about server-side and client-side languages :)

 

PHP is a server-side language. So, your browser calls for somepage.php, the code in that file is run, and the output is sent back to the persons browser. So, once the page is loaded, PHP has done it's job. If you want to run more PHP code (like deleting a user), the browser needs to call another PHP file.

 

Give me a few and I should be able to whip something simple up. But, I would start reading up some more on PHP. I recommend this tutorial: http://devzone.zend.com/node/view/id/627

Link to comment
Share on other sites

Ill definitely give that a read, just in a time crunch to finish this section. I have it so if you are Admin you will be redirected into delete.php, which I will use some code to delete the row from mysql. Is that possible?

 if($user['IsAdmin'] == 'y'){ 
               echo '<td align="left">'. '<a href="delete.php">Delete</a>' .'</td>';
            }

Link to comment
Share on other sites

Here is how i would do everything. Feel free to ask questions on parts you don't understand. Couple of notes:

  • I did not test this code
  • I modified your login stuff, cus you need to save who is logged in into a SESSION variable

 

<?php
  if($_SERVER['REQUEST_METHOD'] == 'POST'){
    // Form was posted
    session_start();
    $_SESSION['user'] = null;
    
    //Create a database connection
    $connection = mysql_connect("localhost", "root", "****")
      or die("Database connection failed: " . mysql_error());
    //Select a database to use
    mysql_select_db("testing", $connection)
      or die("Database failed: " . mysql_error());
    
    if(empty($_POST['name']) || empty($_POST['password'])){
      $error = 'Please go back and fill out the form again.';
    }else{
      // Authenticate the user
      $name = mysql_real_escape_string($_POST['name']);
      $pass = mysql_real_escape_string($_POST['password']);
      $q = sprintf("SELECT Username,Pwd,Admin FROM users WHERE Username = '%s' AND Pwd = '%s' LIMIT 1",$name,$pass);
      $result = mysql_query($q)
        or die("Database query failed");
      $user = mysql_fetch_array($result);
      if(!$user){
        $error = 'Invalid Username/Password.';
      }else{
        //Authenticated
        $_SESSION['user'] = $user;
        header('Location: form_feedback.php');
        exit;
      }
    }
  }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
    <title>Login</title>
    <style type="text/css" title="text/css" media="all">
      .error {
        font-weight: bold;
        color: #C00;
      }
    </style>
  </head>
  <body>
    <h1 align='center'>Please Log In</h1>
<?php if($error) print "<p class=\"error\">$error</p>"; ?>
    <form method="post">
      <table align='center' border = '1'>
        <tr>
          <th> Username </th>
          <td> <input type = "text" name = "name" /> </td>
        </tr>
        <tr>
          <th> Password </th>
          <td> <input type = "password" name = "password"/> </td>
        </tr>
        <tr>
          <td colspan ='2' align = 'center'>
            <input type = "submit" value = "Log In"/>
          </td>
        </tr>
      </table>
    </form>
  </body>
</html>

 

<?php
  session_start();

  // Authenticate the user
  if(!$_SESSION['user']){
    header('Location: login.php');
    exit;
  }
  $user = $_SESSION['user'];
  
  //1. Create a database connection
  $connection = mysql_connect("localhost", "root", "****")
    or die("Database connection failed: " . mysql_error());
  //2. Select a database to use
  mysql_select_db("testing", $connection)
    or die("Database failed: " . mysql_error());

  // Delete User
  if($_GET['action'] == 'delete' && $_GET['user']){
    if(!$user['IsAdmin'])
      die("You are not authorized");
    
    $q = sprintf("DELETE FROM users WHERE Username = '%s'",mysql_real_escape_string($_GET['user']));;
    $result = mysql_query($q)
      or die("Database query failed");
    
    // This will redirect them to the same page (without the URL variables)
    // just in case they try to hit refresh
    header('Location: '.$_SERVER['PHP_SELF']);
    exit;
  }

?>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
    <title>Form Feedback</title>
    <style type="text/css" title="text/css" media="all">
      .error {
        font-weight: bold;
        color: #C00;
      }
    </style>
  </head>
  <body>
  
<?php 
  $q = "SELECT Username,Pwd,Admin FROM users";
  $result = mysql_query($q)
    or die("Database query failed");
  // Start the table
  print '<table align="center" border = "1" cellspacing="1" cellpadding="1" width="20%">';
  //Header
  print '<tr><th align="center">Name</th><th align="center">Password</th>';
  if($user['IsAdmin'] == 'y'){
    print '<th align="center">Is Admin</th><th> </th>';
  }
  print '</tr>';
  while($row = mysql_fetch_array($result)){
    printf('<tr><td align="left">%s</td><td align="left">%s</td>',htmlspecialchars($row['Username']),htmlspecialchars($row['Pwd']));
    if($user['IsAdmin'] == 'y'){
      printf('<td align="left">%s</td><td align="center"><a href="?action=delete&user=%s',$row['IsAdmin'],urlencode($row['Username']));
    }
    print '</tr>';
  }
  print '</table>';
?>

  </body>
</html>

Link to comment
Share on other sites

actually your code is pretty simple to understand. The only error I received was on line 19. which is

if($_GET['action'] == 'delete' && $_GET['user']){

which comes from

if($_GET['action'] == 'delete' && $_GET['user']){
    if(!$user['IsAdmin']){
      die("You are not authorized");
    }
    $q = sprintf("DELETE FROM users WHERE Username = '%s'",mysql_real_escape_string($_GET['user']));;
    $result = mysql_query($q)
      or die("Database query failed");
    
    // This will redirect them to the same page (without the URL variables)
    // just in case they try to hit refresh
    header('Location: '.$_SERVER['PHP_SELF']);
    exit;
  }

 

Link to comment
Share on other sites

I think my main problem is displaying the data that I retrieve from the query.  I really don't have much of an idea on how to display it, if I want a certain one row,column, or if I wanted to display each and every row. I know people use the mysql_fetch_array, and other techniques, but I don't understand it(even after reading about it)

i guess i'll keep trying!

Link to comment
Share on other sites

thanks works great! should I take notifications off? or does it matter?

 

it's debatable. the hard-core coders will say you should code so it doesn't produce notices. my personal opinion...i don't worry about it. notices are off by default for PHP.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.