dots Created with Sketch.
Yogesh Chauhan's Blog

PHP Login System using PDO Part 2: Login using Email or Username

in PHP on December 30, 2019

In this article we saw how to make a registration page:

PHP Login System using PDO Part 1: Create User Registration Page

Now, let's see how to make a login page so that user can login after creating an account.

We are going to use session() in this article so if you want to learn about it from basics I recommend you this article:

The Complete Basic Explanation of PHP Sessions

So, we all know that session() must come before all the HTML tags so I am just going to add to the top of all my code.


<?php

session_start();
 
if(isset($_SESSION["userloggedin"]) && $_SESSION["userloggedin"] === true){
    header("location: homepage.php");
    exit;
}

?>

So, as soon as I start my session, I'll check if the user is logged in. To do do, I am just going to check if the userloggedin variable is set and the value is true or not. I am using this variable because I am going to use the same variable to set true after user is logged in.

If the variable userloggedin is set true then I'll simply take the user to the main page or welcome page.

After that let's add our database credentials and make a PDO connection.


<?php

define('server', 'localhost');
define('user_name', 'root');
define('password', '');
define('database', 'users_yogi');
 
try{
    $pdo = new PDO("mysql:host=" . server . ";dbname=" . database, user_name, password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. " . $e->getMessage());
}
?>

I've used my local host credentials so make sure you change then as per your credentials. 

If you want to learn more about PDO connection, checkout this article:

Learn to Establish Connection using PDO with Example Code

Let's make the login form now.


<h2>Sign In</h2>
    <h4>Please enter your id and password to sign in.</h4>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div class="label_class"><label>Username or Email</label></div>
            <div class="input_class"><input type="text" name="userinput" value="<?php echo $userinput; ?>" required></div>
            <span><?php echo $userinput_error; ?></span>
        </div>    
            <div class="label_class"><label>Password</label></div>
            <div class="input_class"><input type="password" name="password" value="<?php echo $password; ?>" required></div>
            <span><?php echo $password_error; ?></span>
        </div>
        <div class="row" >
        <div class="input_class">
            <input type="submit" class="btn btn-primary" value="Login">
            <input type="reset" class="btn btn-default" value="Reset"></div>
        </div>
    </form>
  • I've kept the format of the form same as registration page so it would be easier to understand as well.
  • I've kept the same <span> tags nearby the input elements to show the errors just like registration form.
  • In this form, user can either enter username or email and he/she will be able to login without any problem. That's why I've kept the name as "userinput" rather than usernae or email.
  • I've also used HTML form validation such as required for input tags as well as password type password.

Now let's add the PHP code to check the user inputs and if they are correct, user will be able to see the homepage.

Let's define some important variables with empty values first:


<?php

$userinput = $password = "";
$userinput_error = $password_error = "";

//code continues

In the userinput variable we will store user's input for username/email and password will be stored in password variables. All the errors will eb stores in variables with _error at the end in their names.

Let's process the data now. We will store the variables using following code:


if($_SERVER["REQUEST_METHOD"] == "POST"){
 
        $userinput = trim($_POST["userinput"]);
        $password = trim($_POST["password"]);

//code continues

Now let's make sure we don't have any errors in those errors variables and go ahead and insert a query to the PDO connection and execute it.


if(empty($userinput_error) && empty($password_error)){

        $sql = "SELECT id, username, password, email FROM users WHERE username = :userinput or email = :userinput";
        if($stmt = $pdo->prepare($sql)){
            $stmt->bindParam(":userinput", $param_userinput, PDO::PARAM_STR);
            $param_userinput = trim($_POST["userinput"]);
            
//code continues

Up to this point we have just prepared the SQL statement to get the id, username, password, email for the username or email entered by the user. We will finish the IF statement after some code inside. 

Now, let's check if the username or email exists in our database:


if($stmt->execute()){
                if($stmt->rowCount() == 1){
                    if($row = $stmt->fetch()){
                        $id = $row["id"];
                        $userinput = $row["username"];
                        $hashed_password = $row["password"];
                        if(password_verify($password, $hashed_password)){
                            session_start();
                            
                            $_SESSION["userloggedin"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["userinput"] = $userinput;                            
                            
                            header("location: hoepage.php");
                        } else{
                            $password_error = "The password you entered was not valid.";
                        }
                    }

//code continues

In the code above, we are executing the statement and checking if we have any user with that username or email address. If so, we will get the data of that user and save it in different variables.

Now for password, we are saving it as a hashed password as we have saved the password using password_hash().

Learn more about password_hash in this blog post:

How to Use password_hash and password_verify to Secure Your User's Data (Especially Passwords)?

After that we are setting the session variables so that we know which user is signed in. After that we will redirect the user to homepage.

At the end there is an error if the password entered by the user doesn't match with the password in the system.

Let's finish those IF statements now.


else{
                    $userinput_error = "No account found with that username or email address.​​​​​";
                }
            } else{
              $alert = "Something went wrong. Please Try Again.";
              echo "<script type='text/javascript'>alert('$alert');</script>";            }
        }
        }
    
    unset($pdo);
}

?>

//end of the code

If the user doesn't exist into the database then it will show an alert with "No account found with that username or email address."

If some unknown error occurs then we will show "Something went wrong" alert and tell user to try again.

At the end we are closing the connection.

That's it. Combine all the code and you will have a login system in PDO.

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
Debugging in WordPress Part 2: WP_DEBUG_LOG and WP_DEBUG_DISPLAYWordPressHow to float an image around texts?CSSJavaScript Input Validation Theme Park Example using throw StatementJavaScriptHow to add Read More Read Less Button using JavaScript?JavaScriptHow to add Laravel to WordPress using Sage theme (and install Tailwind CSS)?PHPCan We Use For Loop to Loop Through Associative Arrays in PHP?PHP