How do I upload a hashed password to my database? - php

I have a basic login page that uses this PHP code to upload directly to my database. When I use this code it works fine and it uploads everything to my table:
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$Email = $_POST['Email'];
$username = $_POST['username'];
$password = ($_POST['password']);
$PhoneNumber = ($_POST['PhoneNumber']);
$query = $con-> prepare("
INSERT INTO Users (fName, lName,Email, username, pass_word,PhoneNumber)
VALUES (:fname, :lname, :Email, :username,:password, :PhoneNumber)
");
$success = $query-> execute ([
'fname' => $fname,
'lname' => $lname,
'Email' => $Email,
'username' => $username,
'password' => $password,
'PhoneNumber' => $PhoneNumber
]);
But when i add the hash password function it just doesnt upload anything to the database at all.
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$Email = $_POST['Email'];
$username = $_POST['username'];
$password = ($_POST['password']);
$PhoneNumber = ($_POST['PhoneNumber']);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = $con-> prepare("
INSERT INTO Users (fName, lName,Email, username, pass_word,PhoneNumber)
VALUES (:fname, :lname, :Email, :username,:password, :PhoneNumber)
");
$success = $query-> execute ([
'fname' => $fname,
'lname' => $lname,
'Email' => $Email,
'username' => $username,
'password' => $hashed_password,
'PhoneNumber' => $PhoneNumber
]);
Update:
I made the changes that were suggested but I am still having the same issue. This is my updated code:
$password = $_POST['password'];
$hashed_password = password_hash($_POST['password'], PASSWORD_BCRYPT, ['cost' => 15]);
$query = $con-> prepare("
INSERT INTO Users (fName, lName,Email, username, pass_word,PhoneNumber)
VALUES (:fname, :lname, :Email, :username,:password, :PhoneNumber)
");
$success = $query-> execute ([
'fname' => $fname,
'lname' => $lname,
'Email' => $Email,
'username' => $username,
'password' => $hashed_password,
'PhoneNumber' => $PhoneNumber
]);

1:
$hashed_password = password_hash($hashed_password, PASSWORD_DEFAULT);
You are hashing an empty string.
You should be hashing the variable containing the password:
$hashed_password = password_hash($_POST['password'], PASSWORD_DEFAULT);
2:
Your SQL query should not contain any variables, this is bad practise and potentially unsafe (for other non-hashed variables).
VALUES (:fname, :lname, :Email, :username,$hashed_password, :PhoneNumber)
But you have $hashed_password as a hardcoded variable. This is incorrect on a syntax level and will cause SQL errors as it's not encased in quotes.
You need to set this value in the ->execute as you do with all the other variables:
$query = $con-> prepare("
INSERT INTO Users (fName, lName,Email, username, pass_word,PhoneNumber)
VALUES (:fname, :lname, :Email, :username, :pwd, :PhoneNumber)
");
$success = $query-> execute ([
'fname' => $fname,
'lname' => $lname,
'Email' => $Email,
'username' => $username,
'pwd' => $hashed_password,
'PhoneNumber' => $PhoneNumber
]);
SECURITY NOTES:
A:
You are not setting a cost value on your PASSWORD_DEFAULT (at time of writing this is BCRYPT) hashing mechanism. It is STRONGLY ENCOURAGED that you set this cost value to as high as possible, rather than the default of 10.
I would suggest setting the cost value to at least 15, and reading the PHP Manual Page, which also sets out how to find the ideal cost value of your server.
$hashed_password = password_hash($password, PASSWORD_BCRYPT, ['cost' => 15]);
B:
I would also highly recommend using one of the ARGON password hashing mechanisms. You will need to recompile PHP with this enabled. I'm sure this will be made easier in coming PHP versions.
C:
I would also highly recommend ensuring your MySQL collations and character sets are UTF8mb4_ prefixed unicode: UTF8mb4_unicode_ci with respect to your password storage column/table (Also ensure your column is long enough*).
* that's what she said!

Related

Basic php/db password encryption

've set up two simple php files for a login/register feature on my android app.
I would like to know a simple way to get it to save/write an encrypted password to the mysql database. at the moment its only writing plain text for password.
Code for register.php is :
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO User (username, email, password) VALUES (?, ?, ?)" );
mysqli_stmt_bind_param($statement, "sss", $username, $email, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
and code for login stuff is:
$password = $_POST["password"];
$username = $_POST["username"];
$statement = mysqli_prepare($con, "SELECT * FROM User WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $username, $email, $password);
$user = array();
while(mysqli_stmt_fetch($statement)) {
$user[username] = $username;
$user[email] = $email;
$user[password] = $password;
}
echo json_encode($user);
mysqli_stmt_close($statement);
mysqli_close($con);
very simple question i know but just learning myself. thanks
EDIT:
Based on Jamesking56's link/ response i've come out with this, but now its not writing to db at all:
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$statement = mysqli_prepare($con, "INSERT INTO User (username, email, password) VALUES (?, ?, ?)" );
mysqli_stmt_bind_param($statement, "sss", $username, $email, $passwordHash);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
If you are using PHP 5.5 or newer, there are some built-in functions for password hashing called password_hash() and password_verify().
Never use MD5 or SHA1 on its own for password hashing as they can be reversed by using rainbow tables.
You should use a hashing mechanism with a secret that you define which gives you hashes which are unique to your application. The 'secret' you create should never be shared through VCS.
A good article about this can be found here: http://www.phptherightway.com/#password_hashing
For anyone using PHP versions lower than 5.5 you can use crypt():
http://php.net/manual/en/function.crypt.php
PHP 5.4 will be unsupported as of 14th September 2015 so please consider upgrading to 5.5.

Unable to INSERT a row in a table with PDO

I want to insert some data into a table using PDO. I looked for some examples and I found that I need to use the functions prepare, bind and then execute, however I can not figure out in my code what I am doing wrong because it inserted nothing and I have no error in the query or php code.
if($_POST){
$account = $_POST['account'];
$password = $_POST['password'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$stmt = 'INSERT INTO employer(account, password, phone, email) VALUES(:account, :password, :phone, :email)';
$stmt = $conn->prepare($stmt);
$stmt->bindParam(':account', $account, PDO::PARAM_STR,100);
$stmt->bindParam(':password',$password, PDO::PARAM_STR,100);
$stmt->bindParam(':phone', $phone, PDO::PARAM_STR,100);
$stmt->bindParam(':email', $email, PDO::PARAM_STR,100);
if ($stmt->execute(array('account' => $account,
'password' => $password,
'phone' => $phone,
'email' =>$email
)
)
){
echo "success";
}else{
echo "error";
}
}
Error detected by #jeroen I was binding twice. So I can bind "either bind before the execute statement or send an array as a parameter, not both"
$stmt = $pdo->prepare('
INSERT INTO employer
(account, password, phone, mail)
values (:account, :password, :phone, :mail)');
$stmt->execute(
array(':account' => $account,
':password' => md5($password),
':phone' => $phone,
':mail' => $email
)
);
if ($pdo->lastInsertId())
return true;
else
return false;

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\wamp\www\PDO.php on line 24

Today, I was trying my code and I got this error : parameter was not defined...
Please, help me:
<?php
$user = 'dbuser';
$pass = 'pwd';
$db = new PDO( 'mysql:host=localhost;
dbname=registration', $user, $pass );
$form = $_POST;
$firstname = $form[ 'firstname' ];
$lastname = $form[ 'lastname' ];
$username = $form[ 'username' ];
$email = $form[ 'email' ];
$password = $form[ 'password1' ];
$dateofbirth = $form[ 'dateofbirth' ];
$monthofbirth = $form[ 'monthofbirth' ];
$yearofbirth = $form[ 'yearofbirth' ];
$gender = $form[ 'gender' ];
$sql = "INSERT INTO members ( firstname, lastname, username, email,
password, dateofbirth, monthofbirth, yearofbirth, gender )
VALUES ( :firstname, :lastname, :username,
:email, :password1, :dateofbirth, :monthofbirth, :yearofbirth,
:gender )";
$query = $db->prepare( $sql );
$query->execute( array( ':firstname'=>$firstname, ':lastname'=> $lastname,
':username'=>$username, ':email'=>$email, ':password'=>$password,
':dateofbirth'=>$dateofbirth, ':monthofbirth'=>$monthofbirth,
':yearofbirth'=>$yearofbirth, ':gender'=>$gender ) );
$result = $query->execute( array( ':firstname'=>$firstname, ':lastname'=>$lastname,
':username'=>$username, ':email'=>$email, ':password'=>$password,
':dateofbirth'=>$dateofbirth, ':monthofbirth'=>$monthofbirth,
':yearofbirth'=>$yearofbirth, ':gender'=>$gender ) );
if ( $result ){
echo "<p>Thank you. You have been registered</p>";
} else {
echo "<p>Sorry, there has been a problem inserting your details. Please contact admin.</p>";
}
?>
In the query string you're passing to PDO::prepare you have this parameter:
:email, :password1
But the array you're passing to PDOStatement::execute doesn't have a :password1 key, it has a :password key instead. It's a simple typo: fix either one or the other.
It might be a good idea to sanitize the actual submitted data before storing it in the DB, though. Things like an email address are easily verified using something like:
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
printf(
'%s is not a valid email address, please fill in correct values',
$email
);
//rebuild form, and return response to client
}
else
{
//carry on validating data, eventually insert it in the DB
}
It's also important not to forget to check the post params using isset, if you don't your code can, and will, generate a lot of notices

Not Submitting to database, with php, mysqli

I can not figure out why it is breaking after passing validation and not submitting to database. Just comes up with blank screen. I have echoed out the new_password and it is encrypting it properly. Am I missing something? or doing something wrong? Any help/advice is appreciated. thanks in advance.
if (isset($_POST['register'])){
//Validation and post variable stuff here but doesn't appear to be any issue with it as I have tested it alot.
}
else if(!$error_msg && !$returned_record && $_POST['register']){
function generateHash($password_1){
if(defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH){
//echo "WE HAVE CRYPT BLOWFISH";
$salt = '$2y$11$'. substr(md5(uniqid(rand(), true)), 0, 22);
return crypt($password_1, $salt);
}//End If
}//End Function generateHash();
$new_password = generateHash($password_1);
//Build our query
$sql = ("INSERT INTO members (username, email, first_name, last_name, country, password_1) VALUES (?,?,?,?,?,?)");
//Prepare our query
$stmt = $mysqli->prepare($sql) or die("PREPARE DIDNT WORK");;
//Bind the fields and there parameters to our query
$stmt->bind_param('ssssss', $username, $email, $first_name, $last_name, $country, $new_password);
//Execute the query
$stmt->execute();
header('Location: http://someurl.com');
exit();
}
Instead of binding the parameters, try this:
$sql = ("INSERT INTO members (username, email, first_name, last_name, country, password_1) VALUES (:username, :email, $first_name, :last_name, :country, :password_1)");
$stmt = $mysqli->prepare($sql) or die("Failed Execution");;
$stmt->execute(array(
':username' => $username,
':email' => $email,
':first_name' => $fname,
':last_name' => $lname,
':country' $country,
':password_1' $password
));
I think i have figured out. I was trying to implement this code into a wordpress template page with a custom loop. I removed all loop/functions and It worked first try. So something in there was causing the issues. Thanks for trying!

checking username against database pdo

The script works to add user data into the db however I want the check if the username is in use but keep running into this error
Fatal error: Call to a member function rowcount() on a non-object in /home/4507408/public_html/registeruser.php on line 78
I cant seem to manage to do it with PDO, any help would be great!
<?php
$form = $_POST;
$username = $form[ 'username' ];
$password = $form[ 'password' ];
$firstname = $form[ 'firstname' ];
$location = $form[ 'location' ];
$age = $form[ 'age' ];
$email = $form[ 'email' ];
$usercheck = $_POST['username'];
$check = "SELECT username FROM use WHERE username = '$usercheck'";
$query = $DBH->prepare( $check );
$query = $DBH->prepare($check);
$query->execute();
$data = $query->fetchALL();
$check2 = $check->rowcount();
//if the name exists it gives an error
if ($check2 != 0) {
die('Sorry, the username '.$_POST['username'].' is already in use.');
}
$sql = "INSERT INTO user ( username, password, firstname, location, age, email ) VALUES ( :username, :password, :firstname, :location, :age, :email )";
$query = $DBH->prepare( $sql );
?>
This line:
$check = "SELECT username FROM use WHERE username = '$usercheck'";
is wrong. use is a SQL reserved word. I assume you meant user. It's also a terrible idea to inject a value into the query string with simple variable substitution. The whole point of PDO is to use parametrized queries: http://us1.php.net/pdo.prepared-statements

Categories