How to login using PDO

Joined
Jul 21, 2021
Messages
2
Reaction score
1
So I recently upgraded to PHP 7 so that I could upgrade to PDO for security reasons, but I'm having a hard time getting the login to work correctly, So far I've managed to get the Signup working so that people can create an account with hashed passwords, which is nice, but the login script is showing "Email or Password wrong" (even though it isn't) and I have a feeling it might be where the passwords are hashed maybe the login needs to also be submitted a certain way? I'm not sure but heres the code for the login... Any help would be really appreciated, I'm new to PDO :)

Login Code..

Code:
<?php
   session_start();

   try {
     include('/var/www/vhosts/myweb.co.uk/httpdocs/PHP/connect.php');

   if (isset($_POST['loginbtn']))
    {

     $email = $_POST['email'];
     $psw = $_POST['psw'];

      if(empty($_POST["email"]) || empty($_POST["psw"]))
           {
                $message = '<label>All fields are required</label>'; 
           }
           else
           {
                $pdo = "SELECT * FROM `users` WHERE email = :email AND psw = :psw";

                $stmt = $dbh->prepare($pdo);
                $stmt->execute(
                     array(
                          'email'     =>     $_POST["email"], 
                          'psw'     =>     $_POST["psw"] 
                     )
                );
                $count = $stmt->rowCount(); 
                if($count > 0) 
                {
                     $_SESSION["email"] = $_POST["email"]; 
                     header("location:../Account/loginsuccessful.php");
                }
                else 
                {
                     $message = '<label>Email or Password is wrong!</label>';
                }       
          } 
       }
  }
     catch(PDOException $error)
     {
          $message = $error->getMessage();
     }
?>

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
if (isset($message)) {
  echo '<label class"text-danger">'. $message .'</label>';
 }
?>
</body>
</html>


Also I will include my Signup code here.... (which is working correctly btw) :)

Code:
<?php

include("/var/www/vhosts/myweb.co.uk/httpdocs/PHP/connect.php");

if (isset($_POST['create'])) {

    $username = $_POST['username'];
    $email = $_POST['email'];
    $psw = $_POST['psw'];
    $pswrepeat = $_POST['pswrepeat'];
    $date = $_POST['date'];

$pdo = $dbh->prepare("SELECT count(*) from `users` WHERE `email` = ?");
    $pdo->bindParam(1, $email, PDO::PARAM_STR);
    $pdo->execute();
    $count = $pdo->fetchColumn();
    if($count > '0'){
    die("email already exists!");
    }else{
    if($psw == $pswrepeat){
    $hashPassword = password_hash($psw, PASSWORD_DEFAULT);
    $hashPassword2 = password_hash($pswrepeat, PASSWORD_DEFAULT);
    $sql = $dbh->prepare("INSERT INTO `users` (email, psw, pswrepeat, username) VALUES (?, ? ,?, ?)");
    $sql->bindParam(1, $email, PDO::PARAM_STR);
    $sql->bindParam(2, $hashPassword, PDO::PARAM_STR);
    $sql->bindParam(3, $hashPassword2, PDO::PARAM_STR);
    $sql->bindParam(4, $username, PDO::PARAM_STR);
    $sql->execute();
    }
   }
 }
 header("location:https://www.myweb.co.uk/Account/signupcomplete.php");
?>
 
Joined
Jul 12, 2020
Messages
89
Reaction score
9
in order for the database entry and the login entry to be compared correctly , either the login needs to be hashed or the db entry needs to be returned to normal in order to be compared.
 
Joined
Jul 21, 2021
Messages
2
Reaction score
1
in order for the database entry and the login entry to be compared correctly , either the login needs to be hashed or the db entry needs to be returned to normal in order to be compared.
Thanks for the info, I have updated my code which seems to work but now it is displaying "email doesnt exist" even though it does..

Here is the new code..

Code:
<?php
   session_start();

    include('/var/www/vhosts/myweb.co.uk/httpdocs/PHP/connect.php');

    if (isset($_POST['loginbtn']))
    {


    $pdo = $dbh->prepare("SELECT count(*) from `users` WHERE `email` = ?");
    $pdo->bindParam(1, $email, PDO::PARAM_STR);
    $pdo->execute();
    $count = $pdo->fetchColumn();
    if($count == '1'){
        
    $sql = $dbh->prepare("SELECT * FROM `users` WHERE `email` = ?");
    $sql->bindParam(1, $email, PDO::PARAM_STR);
    $sql->execute();
    $fetch = $sql->fetch();
    $serverHash = $fetch['psw'];
    $serverEmail = $fetch['email'];
    if(password_verify($psw, $serverHash)) {
    create_session($serverEmail);
    }else{
        echo('password incorrect');
    }
    }else{
        echo('email does not exist');
    }
?>
 
Joined
Jul 12, 2020
Messages
89
Reaction score
9
I think you're using more code than is actually needed, but then again I never used PDO. It's been a while since I've messed with php and sql so this might need need another to help out.

The one thing about SQL and PDO that people don't understand, because of the way they were taught, is that they can create a cascade failure exposing code and directory information which hackers love to expose.

The process is simple:
1. Add the email and password to the database. In this case the password has been hashed so retrieving the information at login for comparison will need to be the same.

2. Logging the user in means retrieving the information without error. You have PDO and SQL queries so here I'll just use the pdo.

Here you are preparing the query but there is no email to match. seems you're loading the entire list of users instead of a single email.
$pdo = $dbh->prepare("SELECT count(*) from `users` WHERE `email` = ?");

The fix:
Code:
$query = "Select from 'users' WHERE 'email' = $_POST['email'] AND  'psw' = " .password_hash($_POST['psw'], PASSWORD_DEFAULT). " ";

$pdo = $dbh->prepare($query);
$pdo->execute();
$_POST['email'] = undefined;
$_POST['psw']    = undefined;

Now there are three(3) responses that could occur:
1. Process Failure response
If the query fails for whatever reason, this causes a cascade failure. Meaning every function and process that depended on it returning "TRUE" will now throw errors exposing code and directory information. We can fix this by notifying the user there was a problem while processing while keeping the web page from collapsing altogether by adding an if statement.

Code:
if($pdo === false){
$message = "The following query failed:
$query"
email( $to,$message);

 echo("We're sorry, an error occurred while processing you're request. <br /> Our techs have been notified and are checking into it. Try again later! <br /> Thanks for your cooperation.");

}
Here we simply email the original query string and notify the visitor of the error.

2. Entry doesn't exist response
If the query returns "TRUE" it should return either an 0 or 1. If it returns "0" it means there's no entry
with that email address and password.
if($pdo == 0){
echo('Email or password are incorrect!');
}

3. User is logged in
if($pdo == 1){
header($user_cp);
}

You will need to tidy it up and check the coding for specifics sut this is a rough draft.
Code:
<?php
   session_start();

    include($dbconn);

if ( isset( $_POST['loginbtn'] ) ) {
  $query = "Select count(*) from 'users' WHERE 'email' = $_POST['email'] AND  'psw' = " .password_hash($_POST['psw'], PASSWORD_DEFAULT). " ";

  $pdo = $dbh->prepare($query);
  $pdo->execute();
  $_POST['email'] = undefined;
  $_POST['psw']    = undefined;

  if( $pdo === false ){
    $message = "The following query failed: $query";
    email( $to,$message);

   echo("We're sorry, an error occurred while processing you're request. <br /> Our techs have been notified and are checking into it. Try again later! <br /> Thanks for your cooperation.");
 }
 else{
    if( $pdo == 0 ){ echo('Email or password are incorrect!');  }
    if( $pdo == 1 ){ header($user_cp); }
  }
}
?>
Anyway something like that. Also notice that script locations and names have been changed to variables. The reason for this, is that over time filenames and locations change which can cause errors. When these errors bog down the server the host may shut down all your scripts forcing it to stop!

Anyway hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top