I have a problem generating Bcrypt passwords. Instead of typing them manual in the hash variable and if statement I would like to generate them in forms HTML. I am not sure how to do that.
<?php
/*in the if statment make sure that the password is the same as in hash variable*/
$options = array('cost' => 12);
echo "Bcrypt: ";
echo $hash = password_hash("yourpassword", PASSWORD_BCRYPT, $options);
echo "<br>";
echo "Verify now:<br>";
if (password_verify('yourpassword', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
<p>Please enter a value to encrypt!</p>
<form action="invite.php">
Key:<br>
<input type="text" name="firstname"><br>
<input type="submit" value="Submit">
</form>
I'll make an attempt at answering this and if this is what the question's about.
You can assign a variable to a POST array (and using a post method for the form) to be passed as the first parameter for both functions, and check if it's not empty and using isset() against a named input/submit.
N.B.: The code below was written to be used inside the same file, as I used action="". If you intend on using this in two separate files, then by all means change the action to the filename used for it.
<?php
/*in the if statment make sure that the password is the same as in hash variable*/
$options = array('cost' => 12);
echo "Bcrypt: ";
if(isset($_POST['submit'])){
if(!empty($_POST['firstname'])){
$their_input = $_POST['firstname'];
echo $hash = password_hash($their_input, PASSWORD_BCRYPT, $options);
echo "<br>";
echo "Verify now:<br>";
if (password_verify($their_input, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
}
else{
echo "You left this empty.";
}
}
?>
<p>Please enter a value to hash!</p>
<form action="" method="post">
Key:<br>
<input type="text" name="firstname"><br>
<input type="submit" name="submit" value="Submit">
</form>
Sidenote: If this is intended for passwords, then you should change the input type to "password" instead of "text".
If you later want to use this as a login system, then have a look at one of ircmaxell's answers https://stackoverflow.com/a/29778421/
If uses PDO and with a prepared statement.
Pulled from his answer:
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above)
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
Important sidenote about column length:
If and when you do decide to use password_hash() or the compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.
You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.
Related
Somebody help me with my code. I create a edit password page containing the Current Password, New Password and Confirm Password. Here's my code:
edit_password.php
<form action="editpassword_process.php" method="post">
<table>
<tr class="form-group has-feedback has-success">
<td><h4>Current Password</h4></td>
<td><div class="control-group input-lg"><input type="password" placeholder="" passfield="true" id="currentpassword" name="currentpassword"></div></td> <!-- class="input-sm" required -->
<td><span id="messagebox"></span></td>
</tr>
<tr>
<td><h4>New Password</h4></td>
<td><div class="control-group input-lg"><input type="password" placeholder="" passfield="true" id="newpassword1" name="newpassword1"></div></td> <!-- required class="input-sm" -->
</tr>
<tr>
<td><h4>Confirm Password</h4></td>
<td><div class="control-group input-lg"><input type="password" placeholder="" passfield="true" id="newpassword2" name="newpassword2" onKeyUp="checkPass(); return false;"></div></td> <!-- required class="input-sm" -->
<span id="confirmMessage" class="confirmMessage"></span>
</tr>
</table>
<button class="btn btn-info">Submit</button>
</form>
Here's my code of editpassword_process.php
<?php
include('connection.php');
$currentpw = $_POST['currentpassword'];
$newpw = $_POST['newpassword1'];
$confirmnewpw = $_POST['newpassword2'];
$res = mysql_query("SELECT user_password FROM `tbl_userlist` WHERE userid = '".$_SESSION['userid']."'");
if($currentpw != mysql_result($res, 0)){
echo "You entered an incorrect password";
}
if($newpw = $confirmnewpw){
$sql = mysql_query("UPDATE tbl_userlist SET user_password = '$newpw' WHERE userid = '".$_SESSION['userid']."'");
}
if($sql){
echo "You have successfully changed your password";
}
else{
echo "The new password and confirm pasword fields must be the same";
}
?>
When i click the submit it appears an alert that shows Validated OK but my database didn't update.
Thank you in advance
There are a few things wrong with your code, but I'll start with why your user password isn't updating. You haven't started a session anywhere in your code. Anywhere you use sessions, you need to start them with:
session_start();
This should be the very first thing you do after your opening <?php tag.
You're assigning(=) and not comparing (==) in a lot of your if(){.. comparison blocks, these will evaluate to TRUE, running the condition.
Now on to the bad, you're using a deprecated library. All mysql_* functions are deprecated and removed as of PHP7. It's best to get ahead of the curve-ball by learning either of these 2 libraries:
PDO
MySQLi Prepared Statements
Either of them will mitigate any SQL Injections you'd come across with your currently vulnerable code. Not to mention the fact that you're storing passwords in plain text. Imagine the implications when (not if) your database is hacked, I hope this isn't a production environment.
PHP makes it super simple to hash a password, just check out:
password_hash()
password_verify()
They'll sort out your password hashing.
To simplify what you're doing, this would be a PDO example along with hashing of your passwords to show you how simple it is to achieve what you're trying to do:
<?php
session_start();
include('connection.php');
$currentpw = $_POST['currentpassword'];
$newpw = $_POST['newpassword1'];
$confirmnewpw = $_POST['newpassword2'];
// start your PDO object
$db = new PDO('mysql:host=localhost;dbname=DATABASE', 'username','password');
$statement = $db->prepare("SELECT user_password FROM `tbl_userlist` WHERE userid = :userid");
$statement->execute(array(':userid' => $_SESSION['userid']));
// check if we have a row
if ($statement->rowCount() > 0) {
$data = $statement->fetch(PDO::FETCH_ASSOC);
$current_password_hash = $data['user_password'];
// check current password is correct.
if (!password_verify($currentpw, $current_password_hash)) {
// wrong "current" password.
die("You entered an incorrect password");
}
// check that both passwords match.
if (trim($confirmnewpw) !== trim($newpw)) {
// new passwords dont match
die("The new password and confirm pasword fields must be the same");
}
// can only get here if passwords match.
// so hash the new password and store in the database.
$newpwhash = password_hash(trim($confirmnewpw), PASSWORD_BCRYPT, array('cost' => 11));
// now lets update table to add new password hash.
$update = $db->prepare("UPDATE tbl_userlist SET user_password = :newpwhash WHERE userid = :userid");
if($update->execute(array(':newpwhash' => $newpwhash, ':userid' => $_SESSION['userid']))) {
// password updated successfully.
die("You have successfully changed your password");
} else {
// failed to update, check logs to ammend.
die('Failed to update password.');
}
} else {
// wrong "current" password.
die("No password found for you...");
}
Needless to say, this will mean you'll have to change your login process too, but it's simple. All you'll need to do is fetch the password and harness password_verify(), and voila, you're sorted.
(Not to mention, a ton more secure.)
Change following things
<?php
session_start(); // Start session as you are using it
include('connection.php');
$currentpw = $_POST['currentpassword'];
$newpw = $_POST['newpassword1'];
$confirmnewpw = $_POST['newpassword2'];
$res = mysql_query("SELECT user_password FROM `tbl_userlist` WHERE userid = '".$_SESSION['userid']."'");
if($currentpw != mysql_result($res, 0)){
echo "You entered an incorrect password";
}
if($newpw = $confirmnewpw){ // Compare using == or ===
$sql = mysql_query("UPDATE tbl_userlist SET user_password = '$newpw' WHERE userid = '".$_SESSION['userid']."'");
// mysql_query("UPDATE tbl_userlist SET user_password = '$newpw' WHERE userid = '".$_SESSION['userid']."'", $connectionVar);
}
if($sql){ // Here You have not executed the query now use $connection->query($sql)
// OR mysql_query($connection,$sql); any other
echo "You have successfully changed your password";
}
else{
echo "The new password and confirm password fields must be the same";
} ?>
when you running this code :
"UPDATE tbl_userlist SET user_password = '$newpw' WHERE userid = '".$_SESSION['userid']."'"
that's mean you update tbl_userlist with criteria userid from session. value from session can be used if you start the session using code session_start();
I'm trying to follow along with a tutorial for creating a login system for a website but some of the code isn't running. Signing up works fine and I can see the entries in my database, but logging in fails even if I have the correct details. Here is my login.php code:
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This variable will be used to re-display the user's username to them in the
// login form if they fail to enter the correct password. It is initialized here
// to an empty value, which will be shown if the user has not submitted the form.
$submitted_username = '';
// This if statement checks to determine whether the login form has been submitted
// If it has, then the login code is run, otherwise the form is displayed
if(!empty($_POST))
{
// This query retrieves the user's information from the database using
// their username.
$query = "SELECT id, username, password, salt, email FROM users WHERE username = :username";
// The parameter values
$query_params = array(
':username' => $_POST['username']
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// This variable tells us whether the user has successfully logged in or not.
// We initialize it to false, assuming they have not.
// If we determine that they have entered the right details, then we switch it to true.
$login_ok = false;
// Retrieve the user data from the database. If $row is false, then the username
// they entered is not registered.
$row = $stmt->fetch();
if($row)
{
// Using the password submitted by the user and the salt stored in the database,
// we now check to see whether the passwords match by hashing the submitted password
// and comparing it to the hashed version already stored in the database.
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
print("Checking password");
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
// If they do, then we flip this to true
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok)
{
// Here I am preparing to store the $row array into the $_SESSION by
// removing the salt and password values from it. Although $_SESSION is
// stored on the server-side, there is no reason to store sensitive values
// in it unless you have to. Thus, it is best practice to remove these
// sensitive values first.
unset($row['salt']);
unset($row['password']);
// This stores the user's data into the session at the index 'user'.
// We will check this index on the private members-only page to determine whether
// or not the user is logged in. We can also use it to retrieve
// the user's details.
$_SESSION['user'] = $row;
// Redirect the user to the private members-only page.
header("Location: secret.html");
die("Redirecting to: secret.html");
}
else
{
// Tell the user they failed
//print("Login Failed.");
// Show them their username again so all they have to do is enter a new
// password. The use of htmlentities prevents XSS attacks. You should
// always use htmlentities on user submitted values before displaying them
// to any users (including the user that submitted them). For more information:
// http://en.wikipedia.org/wiki/XSS_attack
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" value="<?php echo $submitted_username; ?>" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Login" />
</form>
Register
Here is my register.php code:
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['username']))
{
// Note that die() is generally a terrible way of handling user errors
// like this. It is much better to display the error with the form
// and allow the user to correct their mistake. However, that is an
// exercise for you to implement yourself.
die("Please enter a username.");
}
// Ensure that the user has entered a non-empty password
if(empty($_POST['password']))
{
die("Please enter a password.");
}
// Make sure the user entered a valid E-Mail address
// filter_var is a useful PHP function for validating form input, see:
// http://us.php.net/manual/en/function.filter-var.php
// http://us.php.net/manual/en/filter.filters.php
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// We will use this SQL query to see whether the username entered by the
// user is already in use. A SELECT query is used to retrieve data from the database.
// :username is a special token, we will substitute a real value in its place when
// we execute the query.
$query = "
SELECT
1
FROM users
WHERE
username = :username
";
// This contains the definitions for any special tokens that we place in
// our SQL query. In this case, we are defining a value for the token
// :username. It is possible to insert $_POST['username'] directly into
// your $query string; however doing so is very insecure and opens your
// code up to SQL injection exploits. Using tokens prevents this.
// For more information on SQL injections, see Wikipedia:
// http://en.wikipedia.org/wiki/SQL_Injection
$query_params = array(
':username' => $_POST['username']
);
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// The fetch() method returns an array representing the "next" row from
// the selected results, or false if there are no more rows to fetch.
$row = $stmt->fetch();
// If a row was returned, then we know a matching username was found in
// the database already and we should not allow the user to continue.
if($row)
{
die("This username is already in use");
}
// Now we perform the same type of check for the email address, in order
// to ensure that it is unique.
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
die("This email address is already registered");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$query = "
INSERT INTO users (
username,
password,
salt,
email
) VALUES (
:username,
:password,
:salt,
:email
)
";
// A salt is randomly generated here to protect again brute force attacks
// and rainbow table attacks. The following statement generates a hex
// representation of an 8 byte salt. Representing this in hex provides
// no additional security, but makes it easier for humans to read.
// For more information:
// http://en.wikipedia.org/wiki/Salt_%28cryptography%29
// http://en.wikipedia.org/wiki/Brute-force_attack
// http://en.wikipedia.org/wiki/Rainbow_table
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
// This hashes the password with the salt so that it can be stored securely
// in your database. The output of this next statement is a 64 byte hex
// string representing the 32 byte sha256 hash of the password. The original
// password cannot be recovered from the hash. For more information:
// http://en.wikipedia.org/wiki/Cryptographic_hash_function
$password = hash('sha256', $_POST['password'] . $salt);
// Next we hash the hash value 65536 more times. The purpose of this is to
// protect against brute force attacks. Now an attacker must compute the hash 65537
// times for each guess they make against a password, whereas if the password
// were hashed only once the attacker would have been able to make 65537 different
// guesses in the same amount of time instead of only one.
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password . $salt);
}
// Here we prepare our tokens for insertion into the SQL query. We do not
// store the original password; only the hashed version of it. We do store
// the salt (in its plaintext form; this is not a security risk).
$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt,
':email' => $_POST['email']
);
try
{
// Execute the query to create the user
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// This redirects the user back to the login page after they register
header("Location: login.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to login.php");
}
?>
<h1>Register</h1>
<form action="signup.php" method="post">
Username:<br />
<input type="text" name="username" value="" />
<br /><br />
E-Mail:<br />
<input type="text" name="email" value="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Register" />
</form>
I have managed to narrow the problem down to:
$row = $stmt->fetch();
if($row)
{
// Using the password submitted by the user and the salt stored in the database,
// we now check to see whether the passwords match by hashing the submitted password
// and comparing it to the hashed version already stored in the database.
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
print("Checking password");
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
// If they do, then we flip this to true
$login_ok = true;
}
}
as the "print("checking password");" never happens. Can anyone spot a problem in the code? Thank you in advance for your help.
I realised what my problem was... I was attempting to login with the email instead of the username! Thank you all for your help.
when I submit this form i have the same error message all the time . even if i put right or wrong password or don't put password or i write the name of the data base wrong . all of this wrongs i have the same error message :
Please enter a username and password .
so what is the problem . and i am sure about my fields on data base .
<?
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password)
{
$connect = mysql_connect("localhsost","root","adminffpass") or die("Couldent connet to database ");
mysql_select_db("login") or die("No data base found ");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows !=0)
{
while ($row= mysql_fetch_array($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password==$dbpassword)
{
echo "Login successul .<a href='memeberarea.php'>Click to enter member area</a>";
$_SESSION['username'] = $dbusername;
}
else
echo "incorrect password ";
}
else
die ("That user name dosent exist");
}
else
die ("Please enter a username and password");
?>
Even if i put right or wrong password or don't put password or i write the name of the data base wrong . all of this wrongs i have the same error message
Typo: localhsost for one thing. Plus, you may not be able to use mysql_ functions, since they are deprecated and may not be available for you to use.
Plus, your POST arrays may be failing, so make sure your form is a POST method and that your elements bear the name attribute.
I.e.:
<input type="text" name="username">
etc.
if i write wrong name database i don't have any error . why ?"
Because, you're just using or die("Couldent connet to database ") instead of getting the real error mysql_error()
mysql_connect() => http://php.net/manual/en/function.mysql-connect.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Plus, instead of if ($username && $password) you should be using a conditional !empty() for your inputs.
It is also best to use proper and consistent bracing throughout your code.
else{
echo "incorrect password ";
}
etc.
Not doing so, could have adverse effects.
Storing a password hash
Using PDO with prepared statements and password_hash():
Pulled from ircmaxell's answer: https://stackoverflow.com/a/29778421/
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
You may print some information for yourself, so you could see, what's wrong. Change the following line:
echo "incorrect password ";
to something like this:
echo "incorrect password, u:[$username/$dbusername] p:[$password/$dbpassword]";
If you will see that detailed message, you will know, what's wrong.
EDIT: of course, don't left pwd printing in your final code :)
I'm looking for a simple (or as simple as possible) yet secure method for hashing and salting a users password when submitting it to the database and then retrieving from the database. Having spent the past 3 hours researching, there are literally hundreds of different methods that each person will say is the best method.
I'm looking for a relatively simple method that will also keep users accounts secure. Obviously the term secure can be interpreted differently, but i just want it, at the very least, be very difficult for a would-be hacker (or whatever you'd call these saddo's) to gain access to a users account.
I appreciate that i should have at least tried a few things, but they all seem so convoluted and overly secure for my purpose.
I tried using password_hash() but it appears i'm running an earlier PHP version than 5.5. I understand there are issues with the code below, but it's simply a starting point for a person project i'm working on in order to better learn PHP.
Current registration form
$username = $_POST['username'];
$password = $_POST['password'];
try {
$result = $db->prepare("INSERT INTO
user_info
SET
username = :user,
pass = :pass
");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $password);
$result->execute();
}
catch (Exception $e) {
echo "Could not create username";
}
if (isset($_POST['submit'])) {
foreach ($_POST as $field) {
if (empty($field)) {
$fail = true;
}
else {
$continue = false;
}
}
if ($field == $fail) {
echo "You must enter a username and/or password";
}
else {
echo "Your account has been successfully created.";
}
}
The login logic
$username = $_POST['username'];
$password = $_POST['password'];
try {
$result = $db->prepare("SELECT username, pass FROM user_info WHERE username = :user AND BINARY pass = :pass");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
}
catch (Exception $e) {
echo "Could not retrieve data from database";
exit();
}
if ($password = $rows) {
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['loggedin'] = true;
include("inc/redirect.php");
} else {
if (isset($_POST['login'])) {
echo "Username or password incorrect (passwords are case sensitive)";
}
}
Use sha1 function http://www.php.net/manual/en/function.sha1.php
It's really simple. Pass the password in input parameter then save it in the database.
When you want to check if password is correct you just have to compare the sha1(password) with the stored value.
Example :
$passwordEncrypted = sha1($password)
save $passwordEncrypted in your database
When the user want to login :
check this condition :
if (sha1($password) ==$passwordEncrypted )
Here is the complete code :
$username = $_POST['username'];
$password = $_POST['password'];
$passwordEncrypted = sha1($password)
try {
$result = $db->prepare("INSERT INTO
user_info
SET
username = :user,
pass = :pass
");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $passwordEncrypted);
$result->execute();
}
catch (Exception $e) {
echo "Could not create username";
}
if (isset($_POST['submit'])) {
foreach ($_POST as $field) {
if (empty($field)) {
$fail = true;
}
else {
$continue = false;
}
}
if ($field == $fail) {
echo "You must enter a username and/or password";
}
else {
echo "Your account has been successfully created.";
}
}
With password_hash() you are on the right track. For PHP versions 5.3.7 - 5.5 you can use the compatibility pack, later when you switch to a newer PHP version, you can simply remove this php file from your project and the code will still run.
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
Even for lower PHP versions than 5.3.7 you can use the compatibility pack. You only have to edit line 55 and change the algorithm from sprintf("$2y$%02d$", $cost); to sprintf("$2a$%02d$", $cost);. This is of course not optimal, but it is the best you can do for PHP between 5.3 and 5.3.7.
The problem with other algorithms like SHA* or MD5 is, that they are ways too fast. It is possible to calculate about 3 Giga SHA-1 per second with common hardware, that makes brute-forcing too easy. To test a whole english dictionary you would need only a fraction of a millisecond. That's why one should use a hash algorithm with a cost factor like BCrypt or PBKDF2, they allow to control the necessary time to calculate a single hash.
Look at this question:
https://stackoverflow.com/questions/3897434/password-security-sha1-sha256-or-sha512
You can use hash function
http://www.php.net/manual/en/function.hash.php
Use salt and sha256 encryption algorithm
<?php
// create user
$password = $_POST['password'];
$salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$pass = hash("sha256", $salt.$password.$salt);
// save salt and password hash into database
// to validate user
// 1 - get salt and password hash from database
// 2 - prepend and append salt to the posted password
// 3 - encrypt with the same algorithm
// 4 - compare with stored password hash.
I am having some problem connecting properly to the MySQL server using the PDO function.
I can't query what I need from the database and I am not quite sure what PDO functions to use.
I GET 0 as a result of this.
I wish to verify the password and username I enter via the database and make an if statement that launches the session if the information is correct.
Here is my UPDATED code:
<?php
// if a value is given
if (isset($_POST['username' && 'password'));
{
// starts the session created if login info is correct
session_start();
// connectivity to MySQL server
$db = new PDO('mysql:host=host;dbname=name', 'username', 'password');
// information entered in form made into a variable
$username = PDO::quote($_POST['username']);
$password = PDO::quote($_POST['password']);
// after pressing login, checking if the variables exist in the database
if ($_POST['button'] == 'Login')
{
$query = $db->query("SELECT COUNT(*) FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
// Check the number of rows that match the SELECT statement
if($query = $db->fetch(PDO::FETCH_OBJ))
{
echo "No records found";
}
else
{
header("Location: members.php");
$_SESSION['username'] = $_POST['username'];
}
}
// After pressing register, stores variable and adds it in register field
else if ($_POST['register'] == 'Register')
{
header("Location: register.php");
$_SESSION['usernamereg'] = $_POST['username'];
}
// If no button is pressed, send to index
else
{
header("Location: http://www.gjertgjersund.com");
}
// closes the if value is given statement
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Folder </title>
<link rel="stylesheet" type="text/css" href="frontpage.css">
</head>
<body>
<div id="box">
<div id="wrap">
<center>
<img src="./img/logo.png" alt="logo">
<form action='index.php' method='POST' autocomplete='off'>
<div class="usernameform">
<input type='text' name='username' style='border: none; font-size: 20px;'>
</div>
<br />
<div class="passwordform">
<input type='password' name='password' style='border: none; font-size: 20px;'>
</div>
<br />
<div class="registerlogin">
<input type='submit' name='button' value='Login' class='input'>
<input type='submit' name='register' value='Register' class='inputtwo'>
</div>
</form>
</center>
</div>
</div>
</body>
</html>
That's a very good question, partially because it demonstrates a lot of bad practices that, sadly, exist to this day, almost a decade since this question has been posted. Let's sort them out
Connection
I am having some problem connecting properly to the MySQL server using the PDO function.
That's a fair question and nowhere the connection is just a single line of code. Мany important options have to be set, see a canonical connection example I wrote. You can store the connection code in a separate file and then just include it in your scripts.
Password hashing
You should never store plain passwords in your database. Instead, password must be hashed, using a dedicated function made for the purpose - password_hash().
Then, to verify the password, you've go to use password_verify()
Don't move any further until you have your passwords properly hashed. Note that the field size for the hashed password must be 60 characters long.
The code to verify username and password
Finally, now we can write the code. It could be much simpler, just a few lines. Actually, only one condition is needed. We shouldn't provide any details as to whether login or username not found - just "Login and password don't match". So here it goes:
<?php
if (isset($_POST['username']))
{
// get the PDO instance
include 'pdo.php';
// getting the record for the given username
$stmt = $pdo->prepare("SELECT * FROM login WHERE username=?");
$stmt->execute([$_POST['username']]);
$user = $stmt->fetch();
// verifying the password
if ($user && password_verify($_POST['password'], $user['password']))
{
// starts the session created if login info is correct
session_start();
$_SESSION['username'] = $user['username'];
header("Location: members.php");
exit;
} else {
$error = "Login and password don't match";
}
}
Here, we are checking whether such a user exists and whether the password matches in a single condition.
You should not have to use ' in prepared statement and $username is string not integer
$query = $db->query("SELECT * FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
$row_count = $query->rowCount();
//{ remove it
Your if condition is wrong change
// if a value is given
if (isset($_POST['username' && 'password'));
{
to
// if a value is given
if (isset($_POST['username']) and isset($_POST['password']))
{
Codepad
Some databases may return the number of rows returned by a SELECT statement. However, this behaviour is not guaranteed for all databases and should not be relied on see Manual. You can use COUNT(*) and fetchColumn() as in following query to emulate rowCount().
$query = $db->query("SELECT COUNT(*) FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
// Check the number of rows that match the SELECT statement
if($query->fetchColumn() == 0) {
echo "No records found";
}else{
//CODE FOR Success
//Etc
}