YogeshChauhan.com
PHP Login System using PDO Part 2: Login using Email or Username
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.

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

How to check if checkbox is checked or not using JavaScript?JavaScriptHow to Draw a Text Image using JavaScript?JavaScriptsubstring() Method in JavaScriptJavaScriptHow to host Google fonts on your server and add them using CSS?CSSSelect statement in Postgres with examplesPostgresHow to Use password_hash and password_verify to Secure Your User’s Data (Especially Passwords)?PHP