Jump to content

Login Password Encryption Problem


Recommended Posts

Hi, I recently just created a test site to see what I can produce and everything is working fine apart from the login form. Here's the code I have.

 

 

<?php 
    session_start(); 
    // dBase file 
    include "dbConfig.php";
	if ($_GET["op"] == "fail") 
    { 
	echo "<ul><li><h1 class='FailLoginState'>You need to be logged in to access the members area!</h1></li></ul>";
    }
    if ($_GET["op"] == "login") 
    { 
    if (!$_POST["username"] || !$_POST["password"]) 
    { 
    die("You need to provide a username and password."); 
    }
    // Create query 
    $q = "SELECT * FROM `TABLENAMEHERE` " 
    ."WHERE `username`='".$_POST["username"]."' " 
    ."AND `password`='".$_POST["password"]."' "
	."LIMIT 1";
    // Run query 
    $r = mysql_query($q); 
    if ( $obj = @mysql_fetch_object($r) ) 
    { 
    // Login good, create session variables 
    $_SESSION["valid_id"] = $obj->id; 
    $_SESSION["valid_user"] = $_POST["username"]; 
    $_SESSION["valid_time"] = time(); 
    // Redirect to member page 
    Header("Location: members.php"); 
    } 
    else 
    { 
    // Login not successful 
	echo '<form action="?op=login" method="POST">';
	echo 'Username:<br><input class="InputForm" type="text" name="username" id="username"><br>';
	echo '<br>';
	echo 'Password:<br><input class="InputForm" type="password" name="password" id="password"><br>';
	echo '<br>';
	echo '<button type="submit" name="submit" class="InputButton" value="Login">Submit</button>';
	echo '</form>';
	echo '<ul><li></li></ul>';
	echo("<h1 class='FailLoginState'>Sorry, couldn't log you in. Wrong login information.</h1>");
    } 
    } 
    else 
    { 
	echo '<form action="?op=login" method="POST">';
	echo 'Username:<br><input class="InputForm" type="text" name="username" id="username"><br>';
	echo '<br>';
	echo 'Password:<br><input class="InputForm" type="password" name="password" id="password"><br>';
	echo '<br>';
	echo '<button type="submit" name="submit" class="InputButton" value="Login">Submit</button>';
	echo '</form>';
    } 
    ?>

 

 

If they're any bugs or something that looks weird in there it's because I'm new to PHP :P The problem mainly is when the client trys to log in after registering they can't because when they register it encrypts their password with MD5 encryption so when they go to log in, it comes up with the "Incorrect information" error. How do I make it so that it reads that password from the database? Thanks.

Link to comment
Share on other sites

You need to do the same hash to the password that the user enters and THEN compare that to the value in the database. Just using MD5() is a very poor implementation. But, get your script working then you can implement a better hashing method.

Edited by Psycho
Link to comment
Share on other sites

OK, your code had some inefficiencies. For example, you had two instances of the form. You should only have one form and design it for multiple uses (e.g. with and without errors). Additionally, you should have a common method of displaying the errors to make your code more flexible (i.e. not one type of error at top and a different one at bottom). Here is a rewrite that is in a more logical format

 

 

<?php
session_start();
// dBase file
include "dbConfig.php";

$errMsg = "";

//Check if user was brought here due to error
if ($_GET["op"] == "fail")
{
    $errMsg = "You need to be logged in to access the members area!";
}
//Check if Login form was submitted
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
    //Pre-process input data
    $username = trim($_POST["username"]);
    $password = trim($_POST["password"]);
    //Verify fields were entered
    if (empty($username) || empty($password))
    {
        $errMsg = "You need to provide a username and password.";
    }
    else
    {
        // Create query
        $usernameSQL = mysql_real_escape_string($username);
        $passwordSQL = MD5($_POST["password"]); ## Hash password same as it was for the DB value
        //ONE query for data needed - in this case ID
        $q = "SELECT id FROM `TABLENAMEHERE`
              WHERE `username`='{$usernameSQL}'
                AND `password`='{$passwordSQL}'
              LIMIT 1";
        // Run query
        $r = mysql_query($q);
        if(!$r)
        {
            //Error running query
            $errMsg = "There was a problem verifying your credentials. If problem persists contact administrator!";
            //Uncomment next line for debugging purposes
            //echo "Query: {$q}<br>Error: " . mysql_error();
        }
        elseif(!mysql_num_rows($r))
        {
            //User not found
            $errMsg = "Sorry, couldn't log you in. Wrong login information.";
        }
        else
        {
            // Login good, create session variables and redirect
            $_SESSION["valid_id"] = $obj->id;
            $_SESSION["valid_user"] = $username;
            $_SESSION["valid_time"] = time();
            // Redirect to member page
            header("Location: members.php");
        }
    }
}

?>
<h1 class='FailLoginState'><?php echo $errMsg; ?></h1>
<form action="?op=login" method="POST">
Username:<br>
<input class="InputForm" type="text" name="username" id="username" value="<?php echo htmlentities($usernameSQL); ?>">
<br><br>
Password:<br>
<input class="InputForm" type="password" name="password" id="password">
<br><br>
<button type="submit" name="submit" class="InputButton" value="Login">Submit</button>
</form>
Edited by Psycho
Link to comment
Share on other sites

<?php 
    include ("dbConfig.php"); 
    if ( $_GET["op"] == "reg" ) 
    { 
    $bInputFlag = false; 
    foreach ( $_POST as $field ) 
    { 
    if ($field == "") 
    { 
    $bInputFlag = false; 
    } 
    else 
    { 
    $bInputFlag = true; 
    } 
    }  
    if ($bInputFlag == false) 
    { 
    die( "Problem with your registration info. " 
    ."Please go back and try again."); 
    } 
    $q = "INSERT INTO `TABLENAME` (`name`,`password`,`email`) " 
    ."VALUES ('".$_POST["name"]."', " 
    ."PASSWORD('".$_POST["password"]."'), " 
    ."'".$_POST["email"]."')"; 
    $r = mysql_query($q); 
    if ( !mysql_insert_id() ) 
    { 
    die("Error: User not added to database."); 
    } 
    else 
    { 
		Header("Location: register.php?op=thanks");
    } 
    }
    elseif ( $_GET["op"] == "thanks" ) 
    { 
    echo "<h2>Success!</h2>"; 
	echo "Thank you for registering, you should be able to login now.<br>";
	echo "<a href='login.php'>Login</a>";
    } 
    else 
    { 
	echo '<form action="?op=reg" method="POST" accept-charset="UTF-8">';
	echo 'Username:<br><font color="red">*</font><input class="InputForm" type="text" name="name" id="name"><br>';
	echo '<br>';
	echo 'Email:<br><font color="red">*</font><input class="InputForm" type="text" name="email" id="email"><br>';
	echo '<br>';
	echo 'Password:<br><font color="red">*</font><input class="InputForm" type="password" name="password" id="password"><br>';
	echo '<br>';
	echo '<input type="checkbox" name="tick"><font color="gray" size="3"> I agree to the Terms of Use<br>';
	echo '<br>';
	echo '<button type="submit" name="submit" class="InputButton" value="Submit">Submit</button>';
	echo '</form>';
    } 
	?>

 

Hi, thanks for that login, it works great but now that's changed is there anything in this code that I need to change that they both function with each other because at the moment when I register and try to login it won't let me. Thanks again for the help.

Link to comment
Share on other sites

You stated previously that you were hashing the value before storing it in the database. According to that code you are not hashing the password before you store it in the database.

 

You should create a function to do your hashing. Use that function to hash the password before you store it. Then when the user logs in, use the same function to hash thier input value and compare that against what is in the database.

Link to comment
Share on other sites

You stated previously that you were hashing the value before storing it in the database. According to that code you are not hashing the password before you store it in the database.

 

You should create a function to do your hashing. Use that function to hash the password before you store it. Then when the user logs in, use the same function to hash thier input value and compare that against what is in the database.

Isn't that what PASSWORD does?

http://dev.mysql.com/doc/refman/5.1/en/password-hashing.html

 

 

<?php 
    $q = "INSERT INTO `TABLENAME` (`name`,`password`,`email`) " 
    ."VALUES ('".$_POST["name"]."', " 
    ."PASSWORD('".$_POST["password"]."'), " 
    ."'".$_POST["email"]."')"; 

 

 

Edited by Jessica
Link to comment
Share on other sites

 

Yes, it is. And for completeness read this link (I know you know this Jessica): http://dev.mysql.com/doc/refman/5.1/en/encryption-functions.html#function_password

Which basically says "Don't Use This Function in Your Application"

Link to comment
Share on other sites

Yes, it is. And for completeness read this link (I know you know this Jessica): http://dev.mysql.com/doc/refman/5.1/en/encryption-functions.html#function_password

Which basically says "Don't Use This Function in Your Application"

 

Ah okie, cheers. Ok so I'm guessing I'm going to have to completely redo the login form? (Excuse my noobness) :)

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.