Home >Backend Development >PHP Tutorial >How Can I Secure My Code with Password Hashing Using PDO?
Securing Code with Password Hashing using PDO
While the provided code achieves functionality, its security is severely compromised. To enhance security, implementing password hashing with PDO is crucial.
Incorporating Password Hashing into Existing Code
To integrate password hashing, consider employing reputable libraries. For PHP 5.5 use password_hash(), PHP 5.3.7 has password-compat, while others can opt for phpass. Avoid creating custom salt, as libraries manage this process effectively.
Implementing Hashing for Registration
// Establish PDO connection... $username = $_POST["username"]; $email = $_POST["email"]; $password = $_POST["password"]; $hash = password_hash($password, PASSWORD_DEFAULT); // Hashes password $stmt = $dbh->prepare("insert into users set username=?, email=?, password=?"); $stmt->execute([$username, $email, $hash]); echo "<p>Registration successful</p>";
Checking Hashed Passwords for Login
// Establishing PDO connection... $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 }
Advantages of Password Hashing
The above is the detailed content of How Can I Secure My Code with Password Hashing Using PDO?. For more information, please follow other related articles on the PHP Chinese website!