How to Hash Password using PHP password_hash()

May 31, 2020
PHP
Password Hash

Getting Started

I’ve used Bootstrap in this tutorial which is a CSS framework and is included in the downloadable of this tutorial, but if you want, you may download Bootstrap using this link.

Creating a Database

First, we are going to create a database where we put our registered users/members.

I’ve included a .sql file in the downloadable of this tutorial which is a MySQL database file. All you have to do is import the said file.

You should be able to create a database with tables named test.

Creating a Register Form

Next, before we can log in, we first need to register the user/member, and for that, we need to create a register form. Please create a new file, name it as new_account.php and paste the codes below.

<?php
    session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>How to Hash Password using PHP's password_hash()</title>
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <h1 class="page-header text-center">Hash Password using PHP</h1>
    <div class="row">
        <div class="col-sm-4 col-sm-offset-4 panel panel-default" style="padding:20px;">
            <form method="POST" action="register.php">
                <p class="text-center" style="font-size:25px;"><b>Register</b></p>
                <hr>
                <div class="form-group">
                    <label for="email">Email:</label>
                    <input type="email" name="email" id="email" class="form-control" value="<?php echo (!empty($_SESSION['email']) ? $_SESSION['email'] : '') ?>">
                </div>
                <div class="form-group">
                    <label for="password">Password:</label>
                    <input type="password" name="password" id="password" class="form-control" value="<?php echo (!empty($_SESSION['password']) ? $_SESSION['password'] : '') ?>">
                </div>
                <div class="form-group">
                    <label for="confirm_password">Confirm Password:</label>
                    <input type="password" name="confirm_password" id="confirm_password" class="form-control" value="<?php echo (!empty($_SESSION['confirm_password']) ? $_SESSION['confirm_password'] : '') ?>">
                </div>
                <button type="submit" name="register" class="btn btn-success"><span class="glyphicon glyphicon-check"></span> Register</button> <a href="index.php">Already a member? Login</a>
            </form>
            <?php
                if(isset($_SESSION['error'])){
                ?>
                <div class="alert alert-danger text-center" style="margin-top:20px;">
                    <?php echo $_SESSION['error']; ?>
                </div>
                <?php
 
                unset($_SESSION['error']);
            }
 
            ?>
 
        </div>
    </div>
</div>
</body>
</html>

Creating a Register Script

Next, we create the script to register our user. In here, we hash the password of the verified user to be inputted into our database. Please create a new file, name it as register.php and paste the codes below.

<?php
    session_start();
 
    if(isset($_POST['register'])){
        //set database connection
        $conn = new mysqli('localhost', 'root', '', 'test');
 
        //check if password matches the confirm password
        if($_POST['password'] == $_POST['confirm_password']){
            //check if email exists in the database
            $sql = "SELECT * FROM members WHERE email = '".$_POST['email']."'";
            $query = $conn->query($sql);
            if($query->num_rows > 0){
                $_SESSION['error'] = 'Email already taken';
                //return the inputted fields
                $_SESSION['email'] = $_POST['email'];
                header('location: new_account.php');
            }
            else{
                //hash the password
                $hash_password = password_hash($_POST['password'], PASSWORD_DEFAULT);
                $sql = "INSERT INTO members (email, password) VALUES ('".$_POST['email']."', '$hash_password')";
                if($conn->query($sql)){
                    //unset user inputs
                    unset($_SESSION['email']);
                    unset($_SESSION['password']);
                    unset($_SESSION['confirm_password']);
                    $_SESSION['success'] = 'Member registered successfully';
                    header('location: index.php');
                }
                else{
                    $_SESSION['error'] = 'Something went wrong in adding member to database';
                    header('location: new_account.php');
                }
            }
        }
        else{
            $_SESSION['error'] = "Passwords did not match";
            //return the inputted fields
            $_SESSION['email'] = $_POST['email'];
            $_SESSION['password'] = $_POST['password'];
            $_SESSION['confirm_password'] = $_POST['confirm_password'];
            header('location: new_account.php');
        }
    }
    else{
        $_SESSION['error'] = "Fill up register form first";
        header('location: new_account.php');
    }
 
?>

Creating a Login Form

Next, we create our login form where we check our registered users/members. Please create a new file, name it as index.php and paste the codes below.

<?php
    session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>How to Hash Password using PHP's password_hash()</title>
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <h1 class="page-header text-center">Hash Password using PHP</h1>
    <div class="row">
        <div class="col-sm-4 col-sm-offset-4 panel panel-default" style="padding:20px;">
            <form method="POST" action="login.php">
                <p class="text-center" style="font-size:25px;"><b>Login</b></p>
                <hr>
                <div class="form-group">
                    <label for="email">Email:</label>
                    <input type="email" name="email" id="email" class="form-control">
                </div>
                <div class="form-group">
                    <label for="password">Password:</label>
                    <input type="password" name="password" id="password" class="form-control">
                </div>
                <button type="submit" name="login" class="btn btn-primary"><span class="glyphicon glyphicon-log-in"></span> Login</button> <a href="new_account.php">Register a new account</a>
            </form>
            <?php
                if(isset($_SESSION['error'])){
                    ?>
                    <div class="alert alert-danger text-center" style="margin-top:20px;">
                        <?php echo $_SESSION['error']; ?>
                    </div>
                    <?php
 
                    unset($_SESSION['error']);
                }
 
 
 
                if(isset($_SESSION['success'])){
                    ?>
                    <div class="alert alert-success text-center" style="margin-top:20px;">
                        <?php echo $_SESSION['success']; ?>
                    </div>
                    <?php
 
                    unset($_SESSION['success']);
                }
            ?>
        </div>
    </div>
</div>
</body>
</html>

Creating a Login Script

Lastly, we create our login script to check if the user exists in our database. Please create a new file, name it as login.php and paste the codes below.

<?php
    session_start();
 
    if(isset($_POST['login'])){
        //connection
        $conn = new mysqli('localhost', 'root', '', 'test');
 
        //get the user with the email
        $sql = "SELECT * FROM members WHERE email = '".$_POST['email']."'";
        $query = $conn->query($sql);
        if($query->num_rows > 0){
            $row = $query->fetch_assoc();
            //verify password
            if(password_verify($_POST['password'], $row['password'])){
                //action after a successful login
                //for now just message a successful login
                $_SESSION['success'] = 'Login successful';
            }
            else{
                $_SESSION['error'] = 'Password incorrect';
            }
        }
        else{
            $_SESSION['error'] = 'No account with that email';
        }
    }
    else{
        $_SESSION['error'] = 'Fill up login form first';
    }
 
    header('location: index.php');
 
?>

That ends this tutorial. Happy Coding!

Download Here
Facebook Comments

Leave a Reply

Your email address will not be published.