Advertisement
Guest User

Untitled

a guest
Jul 14th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.67 KB | None | 0 0
  1. <?php
  2. // Include config file
  3. require_once 'connect.php';
  4.  
  5. // Define variables and initialize with empty values
  6. $username = $password = "";
  7. $username_err = $password_err = "";
  8.  
  9. // Processing form data when form is submitted
  10. if($_SERVER["REQUEST_METHOD"] == "POST"){
  11.  
  12. // Check if username is empty
  13. if(empty(trim($_POST["username"]))){
  14. $username_err = 'Please enter username.';
  15. } else{
  16. $username = trim($_POST["username"]);
  17. }
  18.  
  19. // Check if password is empty
  20. if(empty(trim($_POST['password']))){
  21. $password_err = 'Please enter your password.';
  22. } else{
  23. $password = trim($_POST['password']);
  24. }
  25.  
  26. // Validate credentials
  27. if(empty($username_err) && empty($password_err)){
  28. // Prepare a select statement
  29. $sql = "SELECT username, password FROM users WHERE username = ?";
  30.  
  31. if($stmt = mysqli_prepare($link, $sql)){
  32. // Bind variables to the prepared statement as parameters
  33. mysqli_stmt_bind_param($stmt, "s", $param_username);
  34.  
  35. // Set parameters
  36. $param_username = $username;
  37.  
  38. // Attempt to execute the prepared statement
  39. if(mysqli_stmt_execute($stmt)){
  40. // Store result
  41. mysqli_stmt_store_result($stmt);
  42.  
  43. // Check if username exists, if yes then verify password
  44. if(mysqli_stmt_num_rows($stmt) == 1){
  45. // Bind result variables
  46. mysqli_stmt_bind_result($stmt, $username, $hashed_password);
  47. if(mysqli_stmt_fetch($stmt)){
  48. if(password_verify($password, $hashed_password)){
  49. /* Password is correct, so start a new session and
  50. save the username to the session */
  51. session_start();
  52. $_SESSION['username'] = $username;
  53. header("location: index.php");
  54. } else{
  55. // Display an error message if password is not valid
  56. $password_err = 'The password you entered was not valid.';
  57. }
  58. }
  59. } else{
  60. // Display an error message if username doesn't exist
  61. $username_err = 'No account found with that username.';
  62. }
  63. } else{
  64. echo "Oops! Something went wrong. Please try again later.";
  65. }
  66. }
  67.  
  68. // Close statement
  69. mysqli_stmt_close($stmt);
  70. }
  71.  
  72. // Close connection
  73. mysqli_close($link);
  74. }
  75. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement