Is it recommended to store password hashes in a separate table or keep them within the User class in PHP?
It is recommended to store password hashes in a separate table for better security practices. By keeping them separate, you can add additional layers of security such as encryption and access control to protect the sensitive information. This separation also helps in case of a data breach, as the password hashes are not easily accessible in the same table as other user information.
// User class with password hash stored in a separate table
class User {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function createUser($username, $password) {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("INSERT INTO users (username) VALUES (?)");
$stmt->bind_param("s", $username);
$stmt->execute();
$userId = $stmt->insert_id;
$stmt = $this->db->prepare("INSERT INTO passwords (user_id, password) VALUES (?, ?)");
$stmt->bind_param("is", $userId, $hashedPassword);
$stmt->execute();
}
public function verifyPassword($username, $password) {
$stmt = $this->db->prepare("SELECT user_id, password FROM users JOIN passwords ON users.id = passwords.user_id WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
if (password_verify($password, $result['password'])) {
return true;
}
return false;
}
}