Using PDO with Password Hashing to Enhance Code Security
To secure your PHP code, it's crucial to utilize password hashing techniques. Avoid relying on vulnerable methods like MD5, which lack security. Password hashing safeguards passwords by generating unique, irreversible values that protect the original passwords from being compromised.
In your provided code, password hashing can be implemented as follows:
Login:
$dbh = new PDO(...); $sql = "SELECT * FROM users WHERE username = :u AND password = :p"; $stmt = $dbh->prepare($sql); $stmt->bindParam(":u", $_POST['username']); $stmt->bindParam(":p", password_hash($_POST['password'], PASSWORD_DEFAULT)); $stmt->execute();
Register:
$dbh = new PDO(...); $username = $_POST["username"]; $email = $_POST["email"]; $password = password_hash($_POST["password"], PASSWORD_DEFAULT); $stmt = $dbh->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)"); $stmt->bindParam(1, $username); $stmt->bindParam(2, $email); $stmt->bindParam(3, $password); $stmt->execute();
Note: Remember to use libraries such as "password-compat" or "phpass" for compatibility with earlier PHP versions before 5.5.
The above is the detailed content of How Can PDO and Password Hashing Improve PHP Application Security?. For more information, please follow other related articles on the PHP Chinese website!