Advertisement
Guest User

Untitled

a guest
Aug 17th, 2016
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. // Updated, correct version of the login function
  2. function login($username, $password, $mysqli) {
  3.  
  4. date_default_timezone_set('Europe/Bucharest');
  5.  
  6. // Using prepared statements means that SQL injection is not possible.
  7. if ($stmt = $mysqli->prepare("SELECT user_id, password, salt, privilages
  8. FROM users
  9. WHERE username = '$username'")) {
  10.  
  11. // Execute the prepared query.
  12. $stmt->execute();
  13. $stmt->store_result();
  14.  
  15. // Get variables from result.
  16. $stmt->bind_result($user_id, $db_password, $salt, $privilage);
  17. $stmt->fetch();
  18.  
  19. // Hash the password with the unique salt.
  20. $password = trim($password);
  21. $password = hash('sha512', $password . $salt);
  22.  
  23. if ($stmt->num_rows == 1) {
  24. // If the user exists we check if the account is locked
  25. // from too many login attempts
  26. if (checkbrute($user_id, $mysqli) == true) {
  27. // Account is locked
  28. // Send an email to user saying their account is locked
  29. return false;
  30. } else {
  31. // Check if the password in the database matches
  32. // the password the user submitted.
  33. if ($db_password == $password) {
  34. // Password is correct!
  35. // Get the user-agent string of the user.
  36. $user_browser = $_SERVER['HTTP_USER_AGENT'];
  37. // XSS protection as we might print this value
  38. $user_id = preg_replace("/[^0-9]+/", "", $user_id);
  39. $_SESSION['user_id'] = $user_id;
  40. // XSS protection as we might print this value
  41. $username = preg_replace("/[^a-zA-Z0-9_\-]+/",
  42. "",
  43. $username);
  44. $_SESSION['username'] = $username;
  45. $_SESSION['privilages'] = $privilages;
  46. $_SESSION['login_string'] = hash('sha512',
  47. $password . $user_browser);
  48. // Login successful.
  49. return true;
  50. } else {
  51. // Password is not correct
  52. // We record this attempt in the database
  53. $now = time();
  54. return false;
  55. }
  56. }
  57. } else {
  58. // No user exists.
  59. return false;
  60. }
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement