Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Authenticates a user against the database and returns the user's ID on success or FALSE on failure
- */
- function log_in(mysqli $con, string $username, string $password): int
- {
- $sql = "SELECT id, password from reg_users where user_name = ?";
- $stmt = mysqli_prepare($con, $sql);
- mysqli_bind_param($stmt, "s", $username);
- mysqli_stmt_execute($stmt);
- if (mysqli_stmt_num_rows($con, $stmt) !== 1) {
- // user not found (invalid username)
- return false;
- }
- $result = mysqli_stmt_get_result($stmt);
- $row = mysqli_fetch_assoc($result);
- $user_id = (int)$row['id'];
- $hashedPassword = $row['password'];
- mysqli_stmt_close($stmt);
- if (!password_verify($password, $hashedPassword)) {
- // Invalid password
- return false;
- }
- if (password_needs_rehash($hashedPassword, PASSWORD_DEFAULT)) {
- $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
- $sql = "UPDATE reg_users SET password = ? WHERE id = ?";
- $stmt = mysqli_prepare($con, $sql);
- mysqli_bind_param($stmt, "si", $hashedPassword, $user_id);
- mysqli_stmt_execute($stmt);
- }
- return $user_id;
- }
Advertisement
Add Comment
Please, Sign In to add comment