How to develop a bootstrap modal login form in PHP and MySQL

Modal is a small dialog box displayed on top of the current screen in a web application. In this topic, we will develop a modal login form in PHP and MySQL. We will use bootstrap modal for this. We will use email id and password to login. For incorrect credentials, we will show error message on the modal form.

To open the modal login form user will use a Login link in a top menu. So, we will have code for a Top Menu, Modal Login and Logout using PHP, MySQL along with jQuery.

Watch YouTube Video

modal bootstrap 5Folders and Files

Below is a screenshot of folder structure and files I am using:

bootstrap login modal

We will use a folder named 'modal_login' under 'htdocs'.

'cfg' folder to keep dbconnect.php used to connect to the MySQL database.
Folder 'css' id for custom stylesheet
Folder 'js' is used for custom JavaScripts
Login modal is defined in login_modal.php

A menubar(top_menu.php) will be displayed on the top and there will be links for Home (index.php) and Login (login.php). When user clicks on Login link, login modal will be displayed. In this topic I will show only login form. Home page will be just for displaying purpose, it is not a complete home page.

Create a MySQL table to store user details

Create a table named 'users' in MySQL database. Table structure is given below:

bootstrap modal login

Table has 5 columns.

  1. id - primary key
  2. email - email id of the user
  3. name - name of the user
  4. password - password for the user
  5. signup_date - date of signup, default is current date, this is not required for login, used as information purpose only


CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `email` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `signup_date` datetime NOT NULL DEFAULT current_timestamp()

INSERT INTO `users` (`id`, `email`, `name`, `password`, `signup_date`) VALUES
(1, '', 'Test User', '202cb962ac59075b964b07152d234b70', '2021-10-13 00:00:00');



Connect to MySQL database (dbconnect.php)

we will create database connection php program in 'cfg' folder and we will include it in other programs.


  $conn = mysqli_connect($server, $userid, $pwd, $dbname);
//Check connection
if (!$conn) 
  	die("Connection Error: " . mysqli_connect_error());

We are using mysqli_connect() method which needs 4 parameters.

  1. server is localhost
  2. userid - we are using root user
  3. password - no password for user root
  4. database name - demo in our case.

For detail MySQL database connection understanding please read topic How to connect to MySQL database in PHP using MySQLi and PDO.

Create a top menu (top_menu.php)

This is the top menu which will display the menu items - Home and Login on a menubar. We will include this menu in home page.


<?php session_start(); 
$email = $login_err_msg = "";
if (isset($_SESSION['login_err_msg']) && ($_SESSION['login_err_msg'] != "")) {
	$login_err_msg = $_SESSION['login_err_msg'];
	$email = $_SESSION['email'];
	$_SESSION['login_err_msg'] = "";
	$_SESSION['email'] = "";

<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
	<meta name="description" content="">
	<title>Modal Login Example</title>
	<link rel="stylesheet" href="">
	<link href="" rel="stylesheet">
	<script  src=""></script>
	<script src=""></script>
	<link rel="stylesheet" href="css/style.css">
	<script src="js/login.js"></script>

	<div class="topmenu">
		<div class="menubar">
			<a id="home" href="index.php"><i class="fa fa-home"></i> Home</a>
			<?php if (isset($_SESSION['name'])) {  ?>
				<div class="logout">
					<a href="logout.php"><i class="fa fa-sign-out"></i> Logout</a>
				<div class="user">
					echo '<span class="welcome">Welcome   </span>' . $_SESSION['name']; ?>
			<?php } else { ?>
				<a id="login" data-toggle="modal" href="#user-login"><i class="fa fa-sign-in"></i> Login</a>
			<?php } ?>
include "login_modal.php";

PHP code at the beginning is explained later, this is for failed login attempt. We have added my custom stylesheet (style.css) and custom JavaScripts (login.js). By checking session variables, we are displaying either Login or Logout link. Look at line 41 for Login. Here, we are calling the login modal by using href="#user-login". This is the login modal which is explained in next step. Also, note that we included login_modal.php at the end.

Create Login Modal (login_modal.php)

When user clicks on login link from the menu, Login modal is displayed. Let us look at the code for login modal below:


<!-- The Modal -->
<div class="modal fade" id="user-login">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Login</h4>
                <button type="button" class="close" data-dismiss="modal" onclick = "clearMsg()">×</button>
            <!-- Modal body -->
            <div class="modal-body">
                <form class="form-1" action="login.php" method="post">
                    <?php if ($login_err_msg != "") { ?>
                        <p class="err-msg"><?php echo $login_err_msg;
                                        } ?></p>
                        <div class="col-md-12 form-group mb-3">
                            <label>Email Id</label>
                            <input type="text" class="form-control" name="email" id="email" value="<?php echo $email; ?>" placeholder="Enter your Email Id" required>

                        <div class="col-md-12 form-group mb-3">
                            <input type="password" class="form-control" name="password" id="password" placeholder="Enter Password" required>
                        <div class="col-md-12 form-group mb-5">
                            <input type="checkbox" class="check" onclick="togglePwd()">Show Password
                        <div class="col-md-12 form-group text-right">
                            <button type="submit" class="btn btn-primary" name="submit">Login</button>

In the modal header we are showing a title and close button. Within modal body we are showing the form two input fields - email id and password. After password we give a checkbox to display/hide password. Then we have a submit button. You must have noticed, I am using two JavaScript functions clearMsg() and togglePwd(). These are explained later.

Write code for modal form submission (login.php)

After entering email id and password when user clicks on Login button, login.php is executed. Let's see the code below for login.php.


include "cfg/dbconnect.php";

if (isset($_POST['submit'])) {    // if Form is submitted
	$email = trim($_POST['email']);
	$password = trim($_POST['password']);
	$password = md5($password);

	$sql = "select * from users where email = '$email' and password = '$password'";
	$result = mysqli_query($conn,$sql);
	if (mysqli_num_rows($result) > 0) {
		$row = mysqli_fetch_array($result);
		$_SESSION['name'] = $row['name'];
		$_SESSION['userid'] = $email;
	else {
		$_SESSION['email'] = $email;
		$_SESSION['login_err_msg'] = "Incorrect Email id or Password";

This is very simple and self-explanatory. Simply take the values entered by the user and check them against values stored in the database table. If matching row found then it is successful login else it is a failed login.

For successful login, set two session variables $_SESSION['name'] and $_SESSION['userid'] and redirect the user to the home page.

For failed attempt, we are also creating two session variables, one is for email and other is for error message. $_SESSION['login_err_msg'] will be displayed in the modal. Then I am redirecting the user to the Home page and there will check if error exists then show the modal with the error message.

Below code is added at the beginning of top_menu.php to display error message as mentioned before.

$email = $login_err_msg = ""; 
if (isset($_SESSION['login_err_msg']) && ($_SESSION['login_err_msg'] != "")) {
  $login_err_msg = $_SESSION['login_err_msg']; 
  $email = $_SESSION['email']; 
  $_SESSION['login_err_msg'] = "";
  $_SESSION['email'] = "";

Just check if session values exist for those two session variables, then put them in two php variables and make those session variables empty. Now, see the modal where we are displaying the error message just after <form> tag.

Create Home Page (index.php)

We will not design a complete home page here. We will just display a heading to show that it is a home page. But two things we will be doing in Home page - 1) scripts to show active page in the menubar 2) scripts to check for login error and display Login modal. See the code below:


<?php include 'top_menu.php';?>

<h1> You are at Home Page </h1>
  $(document).ready(function() { 

  $(function () {
  	<?php if ($login_err_msg != "") { 
  		$login_err_msg = ""; ?>
	<?php } ?>

First script is adding an active class, so that "Home" will be highlighted in the menubar when clicked. Second script is to check for login error message and if exists then call click() method to show the modal.

Add CSS (style.css)

Let us add below styles. We have already added style.css in top_menu.php.


* {box-sizing: border-box;
body {
  margin: 0;
  font-family: Helvetica, sans-serif;;
h1 {
  text-align: center;
.topmenu {
  overflow: hidden;
  background-color: #0a68b0;
.topmenu a {
  float: left;
  display: block;
  font-size: 17px;
  color: #fff;
  padding: 17px 20px;
  text-decoration: none;
  text-align: center;
.topmenu .menubar {
  padding-left: 20px;
.topmenu {
  background-color: #4e69cc;
  color: #000;
.topmenu a:hover {
  background-color: #4e69cc;
  color: black;
@media  screen and (max-width: 500px) {
  .topmenu a {
    text-align: left;
    width: 100%;
    margin: 0;
    padding: 14px;
    display: block;
    float: none; 

  text-align: center;

  font-weight: bold;
.form-1 {
  margin: 5px auto;
  padding-bottom: 30px;
  border-radius: 7px;
  background: #fff;
.check {
  margin: 5px 0px;
  width: 6%;
  height: 20px;
    float: right;
.topmenu .user{
    float: right;
    margin-top: 15px;
    margin-right: 15px;
  color: #c6f606;
  border: none;
  background: none;
  font-size: 27px;

You can see simple styles are added here. Keep this style.css file in your css folder. One point to note here, since we added "active" class in our home page using jQuery, we must add properties for this class in our stylesheet. So, in style.css, properties for "active" class are added.

Add JavaScript/jQuery (login.js)

You have already seen togglePwd() function is called from login form when checkbox - "Show Password" is clicked. So, here is the code for it. Keep login.js file in js folder.


function togglePwd() {
	// get the object password in a varible
  var pwd = document.getElementById("password");
  if (pwd.type === "password") 
    pwd.type = "text";
    pwd.type = "password";

function clearMsg() {

It is used to show/hide password. In this function, type of input object - password is changed from "text" to "password" and vice versa.

clearMsg() function is called when close button is clicked in the login modal. This is just to clear the error message and the values entered in the modal form when user closes the modal.

Lastly, here is logout.php:



We unset all session variables by using session_unset() function. Then delete the session using session_destroy() function.

php login pageTest the Application

Apache web server and MySQL serivices should be running in XAMPP contropll panel. In the browser run localhost/modal_login. You will see the home page displayed.

bootstrap popup

Click on Login from menu. Login modal should be displayed. Enter email id as '', password as '123' and submit.

modal login bootstrap

You should be able to login successfully and see the home page. Also, you should see user name is displayed on top right corner along with Logout link.

modal login

Also try to login with incorrect emailid/password, you should see modal displayed again with error message displayed on top saying "Incorrect Email id/Password".

Watch YouTube Video

modal login php mysql source codeDownload Source Code

Click on the Download button below to download the source code.

login php codeConclusion

We have seen how you can develop modal login form with a simple menu. This is the simplest menu and the form. In actual project there would be many other things you have to code for. I made it very simple for you, you can always improve it. Hope it will be useful for you.