Advertisement
Guest User

Untitled

a guest
Nov 15th, 2016
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. <?php
  2.  
  3. //login.php
  4.  
  5. /**
  6. * Start the session.
  7. */
  8. session_start();
  9.  
  10. /**
  11. * Include ircmaxell's password_compat library.
  12. */
  13. include("password.php");
  14.  
  15. /**
  16. * Include our MySQL connection.
  17. */
  18. include("database.class.php");
  19. $conn = dbConn::getConnection();
  20.  
  21. //If the POST var "login" exists (our submit button), then we can
  22. //assume that the user has submitted the login form.
  23.  
  24. if(isset($_POST['login'])){
  25.  
  26. //Retrieve the field values from our login form.
  27. $username = !empty($_POST['username']) ? trim($_POST['username']) : null;
  28. $passwordAttempt = !empty($_POST['password']) ? trim($_POST['password']) : null;
  29.  
  30. //Retrieve the user account information for the given username.
  31. $sql = "SELECT id, username, password FROM users WHERE username = :username";
  32. $stmt = $conn->prepare($sql);
  33.  
  34. //Bind value.
  35. $stmt->bindValue(':username', $username);
  36.  
  37. //Execute.
  38. $stmt->execute();
  39.  
  40. //Fetch row.
  41. $user = $stmt->fetch(PDO::FETCH_ASSOC);
  42.  
  43. //If $row is FALSE.
  44. if($user === false){
  45. //Could not find a user with that username!
  46. //PS: You might want to handle this error in a more user-friendly manner!
  47. die('Incorrect username / password combination!');
  48. } else{
  49. //User account found. Check to see if the given password matches the
  50. //password hash that we stored in our users table.
  51.  
  52. //Compare the passwords.
  53. $validPassword = password_verify($passwordAttempt, $user['password']);
  54.  
  55. //If $validPassword is TRUE, the login has been successful.
  56. if($validPassword){
  57.  
  58. //Provide the user with a login session.
  59. $_SESSION['user_id'] = $user['id'];
  60. $_SESSION['logged_in'] = time();
  61.  
  62. //Redirect to our protected page, which we called home.php
  63. header('Location: index.php');
  64. exit;
  65.  
  66. } else{
  67. //$validPassword was FALSE. Passwords do not match.
  68. die('Incorrect username / password combination!');
  69. }
  70. }
  71.  
  72. }
  73.  
  74. ?>
  75. <h1>Login</h1>
  76. <form action="login.php" method="post">
  77. <label for="username">Username</label>
  78. <input type="text" id="username" name="username"><br>
  79. <label for="password">Password</label>
  80. <input type="text" id="password" name="password"><br>
  81. <input type="submit" name="login" value="Login">
  82. </form>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement