开发者

Comparing passwords in php and sending it to a database

开发者 https://www.devze.com 2023-03-17 08:41 出处:网络
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 开发者

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");

?>


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.


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 } ?> 


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");


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)


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";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消