Login and Register using PDO in PHP

Submitted by: 
Language: 
Visitors have accessed this post 897 times.

Getting Started

I've used Bootstrap 4 and Font Awesome 5 in this tutorial and are included in the downloadables but if you want, you can download them yourself using the links below.

For Bootstrap
For Font-awesome

Creating our Database

Next, we create the database that we are going to filter in this tutorial.

I've included a SQL file in the downloadable of this tutorial. All you have to do is import the said file. If you have no idea on how to import, please visit my tutorial How import .sql file to restore MySQL database.

You should be able to create a database named dbase.

Creating our Connection

Next, we create our connection to our database using the PDO extension.

Create a new file, name it as conn.php and paste the codes below.

  1. <?php
  2.  
  3. $host = 'localhost';
  4. $db = 'dbase';
  5. $user = 'root';
  6. $pass = '';
  7. $charset = 'utf8mb4';
  8.  
  9. $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
  10. $options = [
  11. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  12. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  13. PDO::ATTR_EMULATE_PREPARES => false,
  14. ];
  15. $pdo = new PDO($dsn, $user, $pass, $options);
  16.  
  17. ?>

Creating our Login Form

Next, we are going to create our login form.

Create a new file, name it as index.php and paste the codes below.

  1. <?php session_start(); ?>
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <title>Login and Register using PDO in PHP</title>
  7. <link rel="stylesheet" type="text/css" href="bootstrap4/css/bootstrap.min.css">
  8. <script src="font-awesome/fontawesome-all.min.js"></script>
  9. </head>
  10. <body>
  11. <div class="container">
  12. <h1 class="text-center" style="margin-top:30px;">Login and Register using PDO</h1>
  13. <hr>
  14. <div class="row justify-content-md-center">
  15. <div class="col-md-5">
  16. <?php
  17. if(isset($_SESSION['error'])){
  18. echo "
  19. <div class='alert alert-danger text-center'>
  20. <i class='fas fa-exclamation-triangle'></i> ".$_SESSION['error']."
  21. </div>
  22. ";
  23.  
  24. //unset error
  25. unset($_SESSION['error']);
  26. }
  27.  
  28. if(isset($_SESSION['success'])){
  29. echo "
  30. <div class='alert alert-success text-center'>
  31. <i class='fas fa-check-circle'></i> ".$_SESSION['success']."
  32. </div>
  33. ";
  34.  
  35. //unset success
  36. unset($_SESSION['success']);
  37. }
  38. ?>
  39. <div class="card">
  40. <div class="card-body">
  41. <h5 class="card-title text-center">Sign in your account</h5>
  42. <hr>
  43. <form method="POST" action="login.php">
  44. <div class="form-group row">
  45. <label for="email" class="col-3 col-form-label">Email</label>
  46. <div class="col-9">
  47. <input class="form-control" type="email" id="email" name="email" value="<?php echo (isset($_SESSION['email'])) ? $_SESSION['email'] : ''; unset($_SESSION['email']) ?>" placeholder="input email" required>
  48. </div>
  49. </div>
  50. <div class="form-group row">
  51. <label for="password" class="col-3 col-form-label">Password</label>
  52. <div class="col-9">
  53. <input class="form-control" type="password" id="password" name="password" value="<?php echo (isset($_SESSION['password'])) ? $_SESSION['password'] : ''; unset($_SESSION['password']) ?>" placeholder="input password" required>
  54. </div>
  55. </div>
  56. <hr>
  57. <div>
  58. <button type="submit" class="btn btn-primary" name="login"><i class="fas fa-sign-in-alt"></i> Login</button>
  59. <a href="register_form.php">Register a new account</a>
  60. </div>
  61. </form>
  62. </div>
  63. </div>
  64. </div>
  65. </div>
  66. </body>
  67. </html>

Creating our Login Script

Next, we create the script that verifies our users.

Create a new file, name it as index.php and paste the codes below.

  1. <?php
  2. //start PHP session
  3.  
  4. //check if login form is submitted
  5. if(isset($_POST['login'])){
  6. //assign variables to post values
  7. $email = $_POST['email'];
  8. $password = $_POST['password'];
  9.  
  10. //include our database connection
  11. include 'conn.php';
  12.  
  13. //get the user with email
  14. $stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
  15.  
  16. try{
  17. $stmt->execute(['email' => $email]);
  18.  
  19. //check if email exist
  20. if($stmt->rowCount() > 0){
  21. //get the row
  22. $user = $stmt->fetch();
  23.  
  24. //validate inputted password with $user password
  25. if(password_verify($password, $user['password'])){
  26. //action after a successful login
  27. //for now just message a successful login
  28. $_SESSION['success'] = 'User verification successful';
  29. }
  30. else{
  31. //return the values to the user
  32. $_SESSION['email'] = $email;
  33. $_SESSION['password'] = $password;
  34.  
  35. $_SESSION['error'] = 'Incorrect password';
  36. }
  37.  
  38. }
  39. else{
  40. //return the values to the user
  41. $_SESSION['email'] = $email;
  42. $_SESSION['password'] = $password;
  43.  
  44. $_SESSION['error'] = 'No account associated with the email';
  45. }
  46.  
  47. }
  48. catch(PDOException $e){
  49. $_SESSION['error'] = $e->getMessage();
  50. }
  51.  
  52. }
  53. else{
  54. $_SESSION['error'] = 'Fill up login form first';
  55. }
  56.  
  57. header('location: index.php');
  58. ?>

Creating our Register Form

Next, we create a register form so that new user can be added to our lists of users.

Create a new file, name it as register_form.php and paste the codes below.

  1. <?php session_start(); ?>
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <title>Login and Register using PDO in PHP</title>
  7. <link rel="stylesheet" type="text/css" href="bootstrap4/css/bootstrap.min.css">
  8. <script src="font-awesome/fontawesome-all.min.js"></script>
  9. </head>
  10. <body>
  11. <div class="container">
  12. <h1 class="text-center" style="margin-top:30px;">Login and Register using PDO</h1>
  13. <hr>
  14. <div class="row justify-content-md-center">
  15. <div class="col-md-5">
  16. <?php
  17. if(isset($_SESSION['error'])){
  18. echo "
  19. <div class='alert alert-danger text-center'>
  20. <i class='fas fa-exclamation-triangle'></i> ".$_SESSION['error']."
  21. </div>
  22. ";
  23.  
  24. //unset error
  25. unset($_SESSION['error']);
  26. }
  27.  
  28. if(isset($_SESSION['success'])){
  29. echo "
  30. <div class='alert alert-success text-center'>
  31. <i class='fas fa-check-circle'></i> ".$_SESSION['success']."
  32. </div>
  33. ";
  34.  
  35. //unset success
  36. unset($_SESSION['success']);
  37. }
  38. ?>
  39. <div class="card">
  40. <div class="card-body">
  41. <h5 class="card-title text-center">Register a new account</h5>
  42. <hr>
  43. <form method="POST" action="register.php">
  44. <div class="form-group row">
  45. <label for="email" class="col-3 col-form-label">Email</label>
  46. <div class="col-9">
  47. <input class="form-control" type="email" id="email" name="email" value="<?php echo (isset($_SESSION['email'])) ? $_SESSION['email'] : ''; unset($_SESSION['email']) ?>" placeholder="input email" required>
  48. </div>
  49. </div>
  50. <div class="form-group row">
  51. <label for="password" class="col-3 col-form-label">Password</label>
  52. <div class="col-9">
  53. <input class="form-control" type="password" id="password" name="password" value="<?php echo (isset($_SESSION['password'])) ? $_SESSION['password'] : ''; unset($_SESSION['password']) ?>" placeholder="input password" required>
  54. </div>
  55. </div>
  56. <div class="form-group row">
  57. <label for="confirm" class="col-3 col-form-label">Confirm</label>
  58. <div class="col-9">
  59. <input class="form-control" type="password" id="confirm" name="confirm" value="<?php echo (isset($_SESSION['confirm'])) ? $_SESSION['confirm'] : ''; unset($_SESSION['confirm']) ?>" placeholder="re-type password">
  60. </div>
  61. </div>
  62. <hr>
  63. <div>
  64. <button type="submit" class="btn btn-success" name="register"><i class="far fa-user"></i> Signup</button>
  65. <a href="index.php">Back to login</a>
  66. </div>
  67. </form>
  68. </div>
  69. </div>
  70. </div>
  71. </div>
  72. </body>
  73. </html>

Creating our Register Script

Lastly, we create the script that registers our user.

Create a new file, name it as register.php and paste the codes below.

  1. <?php
  2. //start PHP session
  3.  
  4. //check if register form is submitted
  5. if(isset($_POST['register'])){
  6. //assign variables to post values
  7. $email = $_POST['email'];
  8. $password = $_POST['password'];
  9. $confirm = $_POST['confirm'];
  10.  
  11. //check if password matches confirm password
  12. if($password != $confirm){
  13. //return the values to the user
  14. $_SESSION['email'] = $email;
  15. $_SESSION['password'] = $password;
  16. $_SESSION['confirm'] = $confirm;
  17.  
  18. //display error
  19. $_SESSION['error'] = 'Passwords did not match';
  20. }
  21. else{
  22. //include our database connection
  23. include 'conn.php';
  24.  
  25. //check if the email is already taken
  26. $stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
  27. $stmt->execute(['email' => $email]);
  28.  
  29. if($stmt->rowCount() > 0){
  30. //return the values to the user
  31. $_SESSION['email'] = $email;
  32. $_SESSION['password'] = $password;
  33. $_SESSION['confirm'] = $confirm;
  34.  
  35. //display error
  36. $_SESSION['error'] = 'Email already taken';
  37. }
  38. else{
  39. //encrypt password using password_hash()
  40. $password = password_hash($password, PASSWORD_DEFAULT);
  41.  
  42. //insert new user to our database
  43. $stmt = $pdo->prepare('INSERT INTO users (email, password) VALUES (:email, :password)');
  44.  
  45. try{
  46. $stmt->execute(['email' => $email, 'password' => $password]);
  47.  
  48. $_SESSION['success'] = 'User verified. You can <a href="index.php">login</a> now';
  49. }
  50. catch(PDOException $e){
  51. $_SESSION['error'] = $e->getMessage();
  52. }
  53.  
  54. }
  55.  
  56. }
  57.  
  58. }
  59. else{
  60. $_SESSION['error'] = 'Fill up registration form first';
  61. }
  62.  
  63. header('location: register_form.php');
  64. ?>

That ends this tutorial. Happy Coding :)


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.