Reputation: 85
I have a working register and login script, but I want to salt the passwords to make sure they are secure against hackers and sql injections
How do I do this? This is my code as follows; thanks HTML
<form method="post">
<input type="text" name="newUsername" placeholder="Username"/>
<input type="password" name="newPassword" placeholder="Password"/>
<input type="submit" name="signUp" value="Sign Up!"/>
</form>
<form method="post">
<input type="text" name="Username" placeholder="Username"/>
<input type="password" name="Password" placeholder="Password"/>
<input type="submit" name="LogIn" value="Log In"/>
</form>
Then PHP:
if($_POST['signUp']) {
$username = $_POST['newUsername'];
$pass = $_POST['newPassword'];
$signedUp = SignUp($Username,$pass);
echo $signUpCode[$signedUp]; // See the SignUp function in prefunc.php
} elseif($_POST['LogIn']) {
$username = $_POST['Username'];
$password = $_POST['Password'];
$loggedIn = LogIn($username,$password);
echo $logInCode[$loggedIn];
}
$signUpCode = Array(
"-3"=>"Logged in already - can't sign up!",
"-2"=>"Username already exists!",
"-1"=>"Failed to sign up - please try again!",
"1"=>"Signed up, and logged in successfully!"
);
function SignUp($Username,$Password) {
$Username = preg_replace("/[^a-zA-Z0-9]/","",$Username);
$u = mysql_query("SELECT * FROM Users WHERE LOWER(Username)=LOWER('$Username')");
if(getCurrentId()){
return -3;
}
if(!mysql_num_rows($u)) {
mysql_query("INSERT INTO Users SET Username='$Username',Password=''$Password") or die(mysql_error());
$u = mysql_query("SELECT * FROM Users WHERE LOWER(Username)=LOWER('$Username')");
if(mysql_num_rows($u)) {
LogIn($Username,$Password);
return 1;
} else {
return -1;
}
}
return -2;
}
Upvotes: 0
Views: 80
Reputation: 71384
A couple of notes:
password_hash()
and password_verify()
for this purpose. These are the best "out of the box" functions in PHP for password hashingUsage example:
$password_hash = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO users (Username, Password) VALUES ('{$username}', '{$password_hash}')";
mysql_*
functionality for anything. This is deprecated functionality. Use mysqli
or PDO
.mysqli
or PDO
you should be using prepared statements with bound parameters. Currently your code is subject to SQL injection as you are doing nothing to escape the user input before trying to use it in your query. Very, very bad practice.Using a parametrized prepared statement, your query would look something like:
$query = "INSERT INTO users (Username, Password) VALUES (:username, :password_hash)";
You would then prepare and execute this. I am not going to go into detail here as there are hundred of thousands of examples on the web of how to do this.
Upvotes: 1