How do I use password hashing with PDO to make my code more secure?

My code is actually working but it's not at all secure, I don't want to use MD5 as it's not all that secure. I've been looking up password hashing but I'm not sure how I would incorporate it into my code.

Login:

require_once __DIR__.'/config.php';
session_start();

$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);

$sql = "SELECT * FROM users WHERE username = :u AND password = :p";
$query = $dbh->prepare($sql); // prepare
$params = array(":u" => $_POST['username'], ":p" => $_POST['password']);
$query->execute($params); // execute

$results = $query->fetchAll(); // then fetch


//hash passwords pls

if (count($results) > 0 ){
$firstrow = $results[0];
$_SESSION['username'] = $firstrow['username'];
echo "Hello $username you have successfully logged in";
//header ("location:.php");
}
else{
echo "Login Has Failed";
return;
} 

Register:

$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);

$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];

$stmt = $dbh->prepare("insert into users set username='".$username."', email='".$email."', password='".$password."' ");
$stmt->execute();
echo "<p>Thank you, you are registered</p>";

Could anyone show me how to incorporate it into the code I have?

Answers 1

  • Just use a library. Seriously. They exist for a reason.

    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
    }
    

Related Articles