3

I am making a login in page and i am a beginner programmer i need to know what function to compare the passwords with then if they do not match tell the user that they dont match and then i need to encrypt them to be sent to the database

Thank you

This is what i have so far:

<?php

$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Email = $_POST['Email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];

if ($&&$password&&$Email&&$Firstname&&$Lastname)
{

if int strcmp ( string $password , string $password2 )
{

$connect = mysql_connect("localhost","root","power1") or die("couldn't connect!");
mysql_select_db("members") or die ("couldnt find db!");

INSERT INTO users (Firstname, Lastname, Email, password,...)
VALUES ($Firstname, $Lastname, $Email, $password, $password2,...)

}
else
    die("Your Passswords do not match") 

}
else
    die("Please enter your credentials");

?>
spencer
  • 33
  • 3
  • 4
  • 9

5 Answers5

5

I think that it is great that you came here to ask for help and I love that you've dived into exactly what you want to do.

<?php

$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Email = $_POST['Email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];

So far, this is great. You've created some variables, such as $Firstname, that are easier to read and type than $_POST['Firstname']. Many PHP programmers will do this.

What you have to be careful of, though, is that nothing is guaranteed to exist in the $_POST array. Therefore, things like $_POST['Firstname'] can be undefined. For that reason, you have to test that your desired values exist first.

if ($&&$password&&$Email&&$Firstname&&$Lastname)
{

I believe here is where you wanted to test that the POST values exist. Unfortunately, this is too late, as an error would have already occurred above. You should consider starting your program in this fashion.

<?php

if (isset($_POST['Firstname']) && isset($_POST['Lastname'])
 && isset($_POST['Email'])     && isset($_POST['password'])
 && isset($_POST['password2']))
{
    $Firstname = $_POST['Firstname'];
    $Lastname = $_POST['Lastname'];
    $Email = $_POST['Email'];
    $password = $_POST['password'];
    $password2 = $_POST['password2'];

    // rest of script...
}

In this example, we make sure that all of the POST values we want to use actually exist before we start using them. This example will not encounter any errors if POST values are missing.

if int strcmp ( string $password , string $password2 )
{

You have the right idea, but you do not actually need to use strcmp to compare two strings for equality in PHP. Instead, you may simply use the == operator.

if ($password == $password2)
{

If you really wanted to use strcmp, we can learn from the documentation page http://php.net/strcmp that the function returns zero if the strings are equal. Therefore, we could use this.

if (strcmp($password, $password2) == 0)
{

After you've made sure the passwords match, this is when you'd want to hash the password. Note that hashing is different than encryption: hashing is one-way, meaning that once the password is hashed you cannot take the hash code and get back the password; on the other hand, encryption can be reversed. Because we never-ever want bad guys to know what someone's password actually is, we should hash the password rather than encrypt it.

Of course, the strength of a hash is only as good as the hashing algorithm, and there are many available. sha1 is decently strong and fine for you to use until you are more comfortable with programming.

$password_hash = sha1($password);

You've connected to your database perfectly. Nothing wrong here.

$connect = mysql_connect("localhost","root","power1") or die("couldn't connect!");
mysql_select_db("members") or die ("couldnt find db!");

However, there is a particular way in which you need to query the database.

INSERT INTO users (Firstname, Lastname, Email, password,...)
VALUES ($Firstname, $Lastname, $Email, $password, $password2,...)

This query needs to be given to the database by passing it as a string to the mysql_query function.

$sql_Firstname = mysql_real_escape_string($Firstname);
$sql_Lastname = mysql_real_escape_string($Lastname);
$sql_Email = mysql_real_escape_string($Email);
$sql_password_hash = mysql_real_escape_string($password_hash);

$sql = "INSERT INTO users (Firstname, Lastname, Email, password)"
      ."`VALUES ('$sql_Firstname', '$sql_Lastname', '$sql_Email', '$sql_password_hash')";

mysql_query($sql);

Note a couple things. First of all, I am storing $password_hash in the database instead of $password. This is what we want, as we never want bad guys to hack the database and figure out what people's passwords are. Secondly, notice that I do not construct the SQL string by using $Firstname directly; instead, I only use $sql_Firstname, which is equivalent to $Firstname but has had special characters properly escaped -- this is what the mysql_real_escape_string function does. This is vital for securing yourself against SQL injection attacks, which I recommend you do some reading on: http://php.net/manual/en/security.database.sql-injection.php.

}
else
    die("Your Passswords do not match") 

}
else
    die("Please enter your credentials");

The rest of your program is done well; it is good for you to deliberately handle these possible error cases. Make sure that you continue to consider all possibilities and deal with each one appropriately; doing so will help prevent unknown bugs and security vulnerabilities in your code.

erisco
  • 14,154
  • 2
  • 40
  • 45
  • I have fixed the above problems to the best of my knowledge and it is not adding anything to my database, displaying any errors when there is no data in the fields. What am i doing wrong? Thank you for your help – spencer Jul 02 '11 at 20:37
  • I recommend you read the answer to this question http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php in case there is something configured incorrectly. – erisco Jul 03 '11 at 01:17
2

Although this does not answer your question I think this is the answer you need

Your code has multiple syntax problems. What you should do now is take some basic PHP tutorials, try to make simple scripts to familiarize yourself with the syntax, and only afterwars deal with more complicated things like database connections, login handling, etc.

Here are the problems (in comments):

<?php

$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Email = $_POST['Email'];
$password = $_POST['password']; // first three variables are capitalized and these two are not. This is not a syntax problem but a general conventions problem
$password2 = $_POST['password2'];

if ($&&$password&&$Email&&$Firstname&&$Lastname) // $&&$ does not make any sense
{
// missing indentation (not syntax problem, but readability/convention)    
if int strcmp ( string $password , string $password2 ) // the syntax is if(condition). In you case if(!strcmp($password, $password2))
{

$connect = mysql_connect("localhost","root","power1") or die("couldn't connect!");
mysql_select_db("members") or die ("couldnt find db!");

// MYSQL queries has to be executed with PHP-specific functions, like mysql_query
INSERT INTO users (Firstname, Lastname, Email, password,...)
VALUES ($Firstname, $Lastname, $Email, $password, $password2,...)

}
else
    die("Your Passswords do not match") // missing semicolon 

}
else
    die("Please enter your credentials");
Gabi Purcaru
  • 30,940
  • 9
  • 79
  • 95
  • @Jonathan Leffler what did you do man? The OP asked for the problems, I pointed them out, and you fixed them? That's not the point here. If you wanted to fix his code post a different answer – Gabi Purcaru Jul 03 '11 at 05:45
  • OK - you disagree with what I did; roll it back (as you did). Sorry. It was meant to be helpful, but evidently I got it wrong. (I think I was looking at a review edit which did some weird stuff to your answer too - but I don't remember for sure.) – Jonathan Leffler Jul 03 '11 at 06:23
2

Here You Go I Rewrote It For Ya And Tested It On My Database! Hit me up on trillian later and we can go into depth about stripping bad characters out of the fields and custom error messages. I gotta go for now time to go change out my distributor cap and convert my intake to a Cold Air Intake!!! Hit me up buddy.

<?php
if (isset($_GET['action']) && $_GET['action'] == 'register') {

$key = "Ex6wCoVjh80Iu7ZAraanEEUyJmPHjCIt";

$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Email = $_POST['Email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];

// Function that converts a string to hexadecimal
    function asc2hex ($temp) {
       $data = "";
       $len = strlen($temp);
       for ($i=0; $i<$len; $i++) $data.=sprintf("%02x",ord(substr($temp,$i,1)));
       return $data;
    }

// String encryption function
        function encrypt($password, $key) {
            $result = '';
            for($i=1; $i<=strlen($password); $i++) {
                $char = substr($password, $i-1, 1);
                $keychar = substr($key, ($i % strlen($key))-1, 1);
                $char = chr(ord($char)+ord($keychar));
                $result.=$char;
            }
            return asc2hex($result);
        }

if ($password == $password2){
$con = mysql_connect("localhost","root","power1");
 if (!$con)
   {
   die('Could not connect: ' . mysql_error());
   }

mysql_select_db("members", $con);

// Check If Email Exists 
$email_check = mysql_query("SELECT Email FROM users WHERE Email='$Email'");
$email_count = mysql_num_rows($email_check);
if ($email_count == '0') {
mysql_query("INSERT INTO users (Firstname, Lastname, Email, password) VALUES ('$Firstname', '$Lastname', '$Email', '".encrypt($password, $key)."')");
}else{
echo "There Is Already A User Registered With This Email Address.";
}
}else{
echo "Your Passwords Do Not Match. Please Try Again.<meta http-equiv='REFRESH' content='3;url=login.php'>";
}
}else{
?>
<form method="post" action="?action=register">
<table border="0" cellpadding="0" cellspacing="5" width="377">
<tr>
<td width="74">First Name</td>
<td width="299"><input type="text" name="Firstname" size="20"></td>
</tr>
<tr>
<td width="74">Last Name</td>
<td width="299"><input type="text" name="Lastname" size="20"></td>
</tr>
<tr>
<td width="74">Email</td>
<td width="299"><input type="text" name="Email" size="20"></td>
</tr>
<tr>
<td width="74">Password</td>
<td width="299"><input type="password" name="password" size="20"></td>
</tr>
<tr>
<td width="74">Repeat Password</td>
<td width="299"><input type="password" name="password2" size="20"></td>
</tr>
<tr>
<td width="74"></td>
<td width="299"><input type=submit value="Submit"></td>
</tr>
</table>
</form>
<?php } ?> 
rackemup420
  • 1,600
  • 2
  • 15
  • 37
  • i used different variable other than $password in the encrypt and decrypt functions. If for some reason you get another error (i write quickly :D) just let me know and ill go test it again. – rackemup420 Jul 02 '11 at 19:51
  • oh and i guess you really dont need the decrypt function here, but i thought i would add it to help you out if you need it on another page, like a "Show Password" option or something to the users on a users page or something!!! – rackemup420 Jul 02 '11 at 19:52
  • so if I am understanding correctly all of the $string i need to change to password in my case thanks for you help – spencer Jul 02 '11 at 19:53
  • As it sits now there should be no need for changing any variables, i think i cought them all and changed them for you already. I was saying i wrote it differently in my scripts. Also added in a custom error message at the bottom, forgot it on my last edit. EDIT: you are right i forgot to change one $string in there for you, updated it now should be 100% good for ya. – rackemup420 Jul 02 '11 at 19:55
  • and you would not use the decrypt code unless you need to send them their password or something – spencer Jul 02 '11 at 20:07
  • Right! I use the decrypt function only in my admin section to show me everyones password. – rackemup420 Jul 02 '11 at 20:09
  • also would i use the encryption code again to encrypt password2 for comparision Thank you! – spencer Jul 02 '11 at 20:10
  • No. if you just copy and paste the new code i wrote out for you in my answer, then you dont have to do anything at all to it and it should function 100% properly. – rackemup420 Jul 02 '11 at 20:11
  • Perfect thank you for answering all of my beginner questions! – spencer Jul 02 '11 at 20:14
  • Now you can venture out and take the error messages 1 step further with custom error messages. – rackemup420 Jul 02 '11 at 20:20
  • Spencer you still having problems? shoot me an email @ irollkids@live.com if you wanna hookup on a chat program or something i can help you live. i cant use the chat on here. – rackemup420 Jul 02 '11 at 20:42
1

You can use a function such as md5 (http://php.net/manual/en/function.md5.php) in order to calculate the hash of the password and compare the hashes (and store the password as a hash in the db)

alampada
  • 2,329
  • 1
  • 23
  • 18
0

Well, first of all, you generally hash a password, you don't encrypt it. A popular hash algorithm is md5, PHP provides a built in function to make a md5 hash: md5

It is best practise to salt the hashes of the passwords you store. You should do some reading on that topic, for example here.

Then you would hash the user input with md5 and compare that value with the password-hash stored in the database.

To answer your first question, comparing the two passwords on registration is fairly simple:

$password = trim($_POST['password']);
$password2 = trim($_POST['password2']);
if($password1 === $password2){
echo "Passwords match";
}else{
echo "Password do not match";
}
Community
  • 1
  • 1
wosis
  • 1,209
  • 10
  • 14