How to Create Secure Login Page in PHP/MySQL Part II

This is a continuation of the topic that I have discuss yesterday on How to Create Secure Login Page in PHP/MySQL. Since PDO is too complicated compared with mysqli, I decided to separate this tutorial.
So, here we go.
login.html
Modify the code on our previous tutorial from:
to
login3.php
  1. <?php
  2. $username = $_POST['username'];
  3. $password = $_POST['password'];
  4.  
  5. $conn = new PDO('mysql:host=localhost;dbname=login', 'root', '');
  6.  
  7. $query = "SELECT password, salt
  8. FROM member
  9. WHERE username = :username";
  10.  
  11. $result = $conn->prepare($query);
  12. $result->bindParam(":username", $username);
  13. $result->execute();
  14.  
  15. $number_of_rows = $result->rowCount();
  16.  
  17. if($number_of_rows == 0) // User not found. So, redirect to login_form again.
  18. {
  19. header('Location: login.html');
  20. }
  21.  
  22. $userData = $result->fetch(PDO::FETCH_ASSOC);
  23.  
  24. $hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
  25.  
  26. if($hash != $userData['password']) // Incorrect password. So, redirect to login_form again.
  27. {
  28. header('Location: login.html');
  29. }else{ // Redirect to home page after successful login.
  30. header('Location: home.html');
  31. }
  32. ?>
As you can see above, there are some changes that are far different compared to mysqli.
Take this example:
In mysqli we use this code:
$result = $mysqli->query($query);
This is the equivalent in PDO:
$result = $conn->prepare($query);
Another is difference on how to fetch the record. In mysqli:
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
In PDO:
$userData  = $result->fetch(PDO::FETCH_ASSOC);

4 comments

This is a good step but you miss using the storage by put the code in poor arrangement

This is Great , add me on lutayashafiq@gmail.com

LET'S WORK TOGETHER

YOUR LESSONS ARE SO ENCOURAGING AND EASY TO FOLLOW.....
MAY GOD BLESS YOU MY BROTHER........

WWW.LUTAYASHAFIQH.COM

Write Comment...
EmoticonEmoticon