Advertisement
Guest User

Untitled

a guest
Apr 30th, 2018
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. <?php
  2. // Include config file
  3. require_once 'config.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 = :username";
  30.  
  31. if($stmt = $pdo->prepare($sql)){
  32. // Bind variables to the prepared statement as parameters
  33. $stmt->bindParam(':username', $param_username, PDO::PARAM_STR);
  34.  
  35. // Set parameters
  36. $param_username = trim($_POST["username"]);
  37.  
  38. // Attempt to execute the prepared statement
  39. if($stmt->execute()){
  40. // Check if username exists, if yes then verify password
  41. if($stmt->rowCount() == 1){
  42. if($row = $stmt->fetch()){
  43. $hashed_password = $row['password'];
  44. if(password_verify($password, $hashed_password)){
  45. /* Password is correct, so start a new session and
  46. save the username to the session */
  47. session_start();
  48. $_SESSION['username'] = $username;
  49. header("location: index.php");
  50. } else{
  51. // Display an error message if password is not valid
  52. $password_err = 'The password you entered was not valid.';
  53. }
  54. }
  55. } else{
  56. // Display an error message if username doesn't exist
  57. $username_err = 'No account found with that username.';
  58. }
  59. } else{
  60. echo "Oops! Something went wrong. Please try again later.";
  61. }
  62. }
  63.  
  64. // Close statement
  65. unset($stmt);
  66. }
  67.  
  68. // Close connection
  69. unset($pdo);
  70. }
  71. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement