PHP Login Form with Bcrypt Password and MySQL


Create a new MySQL database named demo and execute the SQL code below:

-- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: May 06, 2017 at 05:10 PM
-- Server version: 5.7.14
-- PHP Version: 7.0.4

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `demo`
--

-- --------------------------------------------------------

--
-- Table structure for table `account`
--

CREATE TABLE `account` (
  `id` int(11) NOT NULL,
  `username` varchar(250) NOT NULL,
  `password` varchar(250) NOT NULL,
  `fullName` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `account`
--

INSERT INTO `account` (`id`, `username`, `password`, `fullName`) VALUES
(1, 'abc', '$2y$10$GXPqJoUF6WsxAvPXmNILVOAJTLLn5e2PoANvvWtnyORRhrDI.AxgC', 'WWWW'),
(2, 'acc1', '$2y$10$L9bmH4TXfploHD0SVZPIy.FE4vZk6/xOexYNp9g60SqENUj5vqoge', 'Account 1');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `account`
--
ALTER TABLE `account`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `account`
--
ALTER TABLE `account`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Create PHP file named connect.php. Use mysqli_connect method connect to demo database with default account:


Username: root
Password:

<?php
	$con = mysqli_connect('localhost', 'root', '', 'demo');
?>




Create PHP file named index.php. This file display login form as below:

<?php
session_start();
require 'database.php';
if(isset($_POST['buttonLogin'])) {
    $stmt = $conn->prepare('select * from account where username = :username');
	$stmt->bindValue('username', $_POST['username']);
	$stmt->execute();
	$account = $stmt->fetch(PDO::FETCH_OBJ);
    if($account != NULL) {
        if (password_verify($_POST['password'], $account->password)){
            $_SESSION['username'] = $_POST['username'];
            header('location:welcome.php');
        } else {
            $error = 'Account Invalid';
        }
    } else {
        $error = 'Account Invalid';
    }
}
?>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form method="post">
        <?php echo isset($error) ? $error : ''; ?>
        <table>
            <tr>
                <td>Username</td>
                <td>
                    <input type="text" name="username">
                </td>
            </tr>
            <tr>
                <td>Password</td>
                <td>
                    <input type="password" name="password">
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Login" name="buttonLogin">
                    <br>
                    <a href="register.php">Sign Up</a>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

Create PHP file named register.php. This file will display register form as below:

<?php
require 'database.php';
if(isset($_POST['buttonSave'])) {
    $stmt = $conn->prepare('insert into account(username, password, fullName) values(:username, :password, :fullName)');
	$stmt->bindValue('username', $_POST['username']);
	$stmt->bindValue('password', password_hash($_POST['password'], PASSWORD_BCRYPT));
	$stmt->bindValue('fullName', $_POST['fullName']);
	$stmt->execute();
	header('location:index.php');
}
?>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form method="post">
        <table>
            <tr>
                <td>Username</td>
                <td>
                    <input type="text" name="username">
                </td>
            </tr>
            <tr>
                <td>Password</td>
                <td>
                    <input type="password" name="password">
                </td>
            </tr>
            <tr>
                <td>Full Name</td>
                <td>
                    <input type="text" name="fullName">
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Save" name="buttonSave">
                </td>
            </tr>
        </table>
</body>
</html>




Create PHP file named welcome.php. This file will value of Session as below:

<?php
session_start();
if(isset($_GET['action']) && $_GET['action'] == 'logout') {
    unset($_SESSION['username']);
    header('location:index.php');
}
?>

Welcome <?php echo $_SESSION['username']; ?>
<br>
<a href="index.php?action=logout">Logout</a> |
<a href="change_profile.php">Change Profile</a>

Create PHP file named change_profile.php. This file will display profile of user as below:

<?php
session_start();
require 'database.php';

$stmt = $conn->prepare('select * from account where username = :username');
$stmt->bindValue('username', $_SESSION['username']);
$stmt->execute();
$account = $stmt->fetch(PDO::FETCH_OBJ);

if(isset($_POST['buttonSave'])) {
    $stmt = $conn->prepare('update account set password = :password,
		fullName = :fullName, username = :username where id = :id');
	$stmt->bindValue('username', $_POST['username']);
	$stmt->bindValue('password', $_POST['password'] == '' ? $account->password : password_hash($_POST['password'], PASSWORD_BCRYPT));
	$stmt->bindValue('fullName', $_POST['fullName']);
    $stmt->bindValue('id', $_POST['id']);
	$stmt->execute();
	header('location:index.php');
}
?>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form method="post">
        <table>
            <tr>
                <td>Id</td>
                <td>
                    <?php echo $account->id; ?>
                    <input type="hidden" name="id"
                        value="<?php echo $account->id; ?>">
                </td>
            </tr>
            <tr>
                <td>Username</td>
                <td>
                    <input type="text" name="username"
                        value="<?php echo $account->username; ?>">
                </td>
            </tr>
            <tr>
                <td>Password</td>
                <td>
                    <input type="password" name="password" >
                </td>
            </tr>
            <tr>
                <td>Full Name</td>
                <td>
                    <input type="text" name="fullName" value="<?php echo $account->fullName; ?>">
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Save" name="buttonSave">
                </td>
            </tr>
        </table>
</body>
</html>




Login Page

Welcome Page

Register Page

Change Profile Page

I recommend you refer to the books below to learn more about the knowledge in this article: