Guest User

Untitled

a guest
Jun 1st, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. /**
  4.  * Authenticates a user against the database and returns the user's ID on success or FALSE on failure
  5.  */
  6. function log_in(mysqli $con, string $username, string $password): int
  7. {
  8.     $sql = "SELECT id, password from reg_users where user_name = ?";
  9.  
  10.     $stmt = mysqli_prepare($con, $sql);
  11.     mysqli_bind_param($stmt, "s", $username);
  12.     mysqli_stmt_execute($stmt);
  13.  
  14.     if (mysqli_stmt_num_rows($con, $stmt) !== 1) {
  15.         // user not found (invalid username)
  16.         return false;
  17.     }
  18.  
  19.     $result = mysqli_stmt_get_result($stmt);
  20.  
  21.     $row = mysqli_fetch_assoc($result);
  22.     $user_id = (int)$row['id'];
  23.     $hashedPassword = $row['password'];
  24.  
  25.     mysqli_stmt_close($stmt);
  26.  
  27.     if (!password_verify($password, $hashedPassword)) {
  28.         // Invalid password
  29.         return false;
  30.     }
  31.  
  32.     if (password_needs_rehash($hashedPassword, PASSWORD_DEFAULT)) {
  33.         $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
  34.  
  35.         $sql = "UPDATE reg_users SET password = ? WHERE id = ?";
  36.  
  37.         $stmt = mysqli_prepare($con, $sql);
  38.         mysqli_bind_param($stmt, "si", $hashedPassword, $user_id);
  39.         mysqli_stmt_execute($stmt);
  40.     }
  41.  
  42.     return $user_id;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment