skip to Main Content

I currently have a login system, which I would like to convert to PDO from Mysqli.

I currently have a website with a database attached with phpMyAdmin/MySQL.

I tried to convert everything and I will now show you the LOGIN.php part of the system since I haven’t touched the signup part yet.

This is what I have.

LOGIN.INC.PHP

    <?php

require_once 'dbh.inc.php';

try {
    $handler = new PDO("mysql:host=$servername;dbname=$dbname",
    $username,
    $password,
    array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
  } catch(PDOException $e){
    echo $e->getName();
    die();
  }

//first we start a session
session_start();

//We then check if the user has clicked the login button
if (isset($_POST['submit'])) {

    //Then we require the database connection
    //require_once 'dbh.inc.php';
    //And we get the data from the login form
    $name = $_POST['name'];
    $password = $_POST['password'];

    //Error handlers
    //Error handlers are important to avoid any mistakes the user might have made when filling out the form!
    //Check if inputs are empty
    if (empty($name) || empty($password)) {
        header("Location: ../index.php?login=empty");
        exit();
    }   
    } else {
        $stmt = $db->prepare("SELECT * FROM users WHERE user_name=:name");
        $stmt->bindParam(':name', $name, PDO::PARAM_STR);

        if ($stmt->execute()) {
            header("location: ../index.php?login=error");
            exit();
        } else { 
            if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            //de-hashing the password
            $hashedpasswordCheck = password_verify($password, $row['user_password']);
            if ($hashedpasswordCheck == false) {
              header("location: ../index.php?login=error");
              exit();

            } elseif ($hashedpasswordCheck == true) {
                //Log in the user here
                $_SESSION['u_id'] = $row['user_id'];
                $_SESSION['u_name'] = $row['user_name'];
                header("location: ../index.php?login=success");
                exit();
              }
            } else {
                header("location: ../index.php?login=error");
                exit();
              }     
        }  
      } 

DBH.INC.PHP

    <?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "loginsystem";


try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname",
    $username,
    $password,
    array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

    $stmt = $conn->prepare("SHOW DATABASES;");

    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $result = $stmt->fetchAll();
    print_r($result);


}
catch(PDOException $e) {
    echo $e->getMessage();
}

$conn = null;

When I try to login I get redirected to this url:

http://localhost/php44/includes/login.inc.php

and receive this printed message/error.

Array ( [0] => Array ( [Database] => imgupload ) [1] => Array ( [Database] => information_schema ) [2] => Array ( [Database] => loginsystem ) [3] => Array ( [Database] => mysql ) [4] => Array ( [Database] => performance_schema ) [5] => Array ( [Database] => phpmyadmin ) [6] => Array ( [Database] => test ) )

What should I do to fix this, so that my login works?

2

Answers


  1. I’ve made some fixes and added comments in to explain what changed:

    LOGIN.INC.PHP

    <?php
    
    //First we start a session
    session_start();
    
    //Then we require the database connection
    require_once 'dbh.inc.php';
    
    // Removed the extra database connection here.
    
    //We then check if the user has clicked the login button
    if (isset($_POST['submit'])) {
    
        //And we get the data from the login form
        $name = $_POST['name'];
        $password = $_POST['password'];
    
        //Error handlers
        //Error handlers are important to avoid any mistakes the user might have made when filling out the form!
        //Check if inputs are empty
        if (empty($name) || empty($password)) {
            header("Location: ../index.php?login=empty");
            exit();
        }   
    //Removed extra 'else' here.
        $stmt = $conn->prepare("SELECT * FROM users WHERE user_name=:name");  // Changed $db to $conn to use the connection from DBH.INC.PHP
        $stmt->bindParam(':name', $name, PDO::PARAM_STR);
    
        if (!$stmt->execute()) {   // Added the ! to say "if this doesn't work, redirect to error"
            header("location: ../index.php?login=error");
            exit();
        } else { 
            if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                //de-hashing the password
                $hashedpasswordCheck = password_verify($password, $row['user_password']);
                if ($hashedpasswordCheck == false) {
                    header("location: ../index.php?login=error");
                    exit();
                } else if ($hashedpasswordCheck == true) {
                    //Log in the user here
                    $_SESSION['u_id'] = $row['user_id'];
                    $_SESSION['u_name'] = $row['user_name'];
                    header("location: ../index.php?login=success");
                    exit();
                }
            } else {
            header("location: ../index.php?login=error");
            exit();
            }     
        }  
    }
    

    DB.INC.PHP

    <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "loginsystem";
    
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname",
        $username,
        $password,
        array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    
        // Removed the query and print of the databases
    
      }
    catch(PDOException $e) {
        echo $e->getMessage();
    }
    // Removed the $conn=null to keep the connection we just set up.
    
    Login or Signup to reply.
  2. Your code is vulnerable to Html Elements Injection and session fixation attack. I have implemented strip_tags() to prevents html element injection attack and have also implemented session_regenerate_id(); to prevent session fixation attack.

    Again since you are login, you only need to initialize session as soon as username and password is verified.

    As for me, I prefer using PDO array method. Anyway I have provided two solution. I first work on your code and then modify it were appropriate. Ensure that database credentials is okay

    Your code

    <?php
    
    //db connect starts
    $db = new PDO (
        'mysql:host=localhost;dbname=loginsystem;charset=utf8', 
        'root', // username
    
        '' // password
    );
    
    
    
    //We then check if the user has clicked the login button
    if (isset($_POST['submit'])) {
        $name = $_POST['name'];
        $password = $_POST['password'];
    
        if ($name =='' && $password =='') {
            header("Location: ../index.php?login=empty");
            exit();
        } 
    
    
            $stmt = $db->prepare("SELECT * FROM users WHERE user_name=:name");
            $stmt->bindParam(':name', $name, PDO::PARAM_STR);
            $stmt->execute();
    
    $count = $stmt->rowCount();
    if( $count == 1 ) {
    $row = $stmt->fetch();
    if(password_verify($password,$row['password'])){
                echo "Password verified and ok";
    
    // initialize session if things where ok.
    session_start();
    
    //Prevent session fixation attack
    session_regenerate_id();
    
    $_SESSION['u_id'] = $row['user_id'];
    $_SESSION['u_name'] = $row['user_name'];
    header("location: ../index.php?login=success");
    exit();
    
    
            }
            else{
                echo "Wrong Password details";
            }
    }
    else {
    
    echo "User does not exist";
    }
    }
    ?>
    

    my code

    <?php
    
    //if (isset($_POST['submit'])) {
    if ($_POST['name'] !='' && $_POST['password']) {
    
    //connect 
    $db = new PDO (
        'mysql:host=localhost;dbname=loginsystem;charset=utf8', 
        'root', // username
    
        '' // password
    );
    
    $name = strip_tags($_POST['name']);
    $password = strip_tags($_POST['password']);
    
    if ($name == ''){
    echo "Username is empty";
    exit();
    }
    if ($password == ''){
    echo "password is empty";
    exit();
    }
    
    $result = $db->prepare('SELECT * FROM users where user_name = :name');
            $result->execute(array(
                ':user_name' => $name));
    $count = $result->rowCount();
    if( $count == 1 ) {
    $row = $result->fetch();
    
      if(password_verify($password,$row['password'])){
                echo "Password verified and ok";
    
    // initialize session if things where ok.
    session_start();
    
    //Prevent session fixation attack
    session_regenerate_id();
    
    $_SESSION['u_id'] = $row['user_id'];
    $_SESSION['u_name'] = $row['user_name'];
    header("location: ../index.php?login=success");
    exit();
    
    
            }
            else{
                echo "Wrong Password details";
            }
    }
    else {
    
    echo "User does not exist";
    }
    
    }
    
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search