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 the Bootstrap modal for this. We will use email id and password to login. For incorrect credentials, we will show an error message on the modal form.
To open the modal login form user will use a Login link in the top menu. So, we will have code for a Top Menu, Modal Login and Logout using PHP, MySQL with jQuery.
Below is a screenshot of folder structure and files I am using:
We will use a folder named 'modal_login' under 'htdocs'.
The 'cfg' folder is to keep dbconnect.php used to connect to the MySQL database.
Folder 'css' is for the custom stylesheet
Folder 'js' is used for the custom JavaScript
Login modal is defined in login_modal.php
A menu bar(top_menu.php) will be displayed on the top and there will be links for Home (index.php) and Login (login.php). When the user clicks on the Login link, the login modal is displayed. In this topic, I will show only the login form. The home page will be just for displaying purposes, it is not a complete home page.
Create a MySQL table to store user details
Create a table named 'users' in MySQL database. The table structure is given below:
The table has 5 columns.
id - primary key
email - email id of the user
name - name of the user
password - password for the user
signup_date - date of signup, default is current date, this is not required for login, used as information purpose only
users.sql
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()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `users` (`id`, `email`, `name`, `password`, `signup_date`) VALUES
(1, 'test@test.com', 'Test User', '202cb962ac59075b964b07152d234b70', '2021-10-13 00:00:00');
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
Connect to MySQL database (dbconnect.php)
We will create a database connection PHP program in the 'cfg' folder and include it in other programs.
PHP code at the beginning is explained later, this is for failed login attempts. We have added my custom stylesheet (style.css) and custom JavaScripts (login.js). By checking session variables, we display either the Login or Logout link. Look at line 41 for Login. Here, we call the login modal using href="#user-login". This is the login modal which is explained in next step. Also, note that we included login_modal.php in the end.
Create Login Modal (login_modal.php)
When the user clicks on the login link from the menu, the login modal is displayed. Let us look at the code for login modal below:
In the modal header, we show a title and close button. Within the modal body, we show the form with two input fields - email id and password. After the password field, we give a checkbox to display/hide the password. Then we have a submit button. You must have noticed that we use two JavaScript functions clearMsg() and togglePwd(). These are explained later.
Write code for modal form submission (login.php)
After entering the email id and password when the user clicks on the Login button, login.php is executed. Let's see the code below for login.php.
login.php
<?php
session_start();
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;
header("location:index.php");
}
else {
$_SESSION['email'] = $email;
$_SESSION['login_err_msg'] = "Incorrect Email id or Password";
header("location:index.php");
}
}
This is very simple and self-explanatory. Take the values entered by the user and check them against values stored in the database table. If a matching row is found then it is a 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 attempts, we are also creating two session variables, one is for the email and the other is for the error message. $_SESSION['login_err_msg'] will be displayed in the modal. Then we redirect the user to the home page and check if an error exists show the modal with the error message.
The below code is added at the beginning of top_menu.php to display the error message as mentioned before.
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 display the error message after the <form> tag.
Create Home Page (index.php)
We will not design a complete home page here. We will display a heading to show that it is a home page. In the Home page, we will add the scripts 1) to show the active page in the menu bar and 2) to check for login errors and display the login modal. See the code below:
index.php
<?php include 'top_menu.php';?>
<h1> You are at Home Page </h1>
<script>
$(document).ready(function() {
$("#home").addClass("active");
});
</script>
<script>
$(function () {
<?php if ($login_err_msg != "") {
$login_err_msg = ""; ?>
$("#login").click();
<?php } ?>
});
</script>
</body>
</html>
The first script is to add an active class to highlight "Home" in the menu bar when clicked. The second script is to check for the login error message and call the click() method to show the modal with the error message.
Add CSS (style.css)
Let us add the below styles. We have already added style.css in top_menu.php.
One point to note here, since we added an "active" class in our home page using jQuery, we must add properties for this class in our stylesheet. So, in style.css, properties for the "active" class are added.
Add JavaScript/jQuery (login.js)
You have already seen togglePwd() function is called from the login form when the checkbox "Show Password" is clicked. So, here is the code for it. Keep the login.js file in the "js" folder.
login.js
function togglePwd() {
// get the object password in a varible
var pwd = document.getElementById("password");
if (pwd.type === "password")
pwd.type = "text";
else
pwd.type = "password";
}
function clearMsg() {
$(".err-msg").html("");
$("#email").val("");
$("#password").val("");
}
It is used to show/hide passwords. In this function, the type of input object password is changed from "text" to "password" and vice versa.
The clearMsg() function is called when the close button is clicked in the login modal. This is to clear the error message and the values entered in the modal form when the user closes the modal.
We unset all session variables by using the session_unset() function. Then delete the session using the session_destroy() function.
Test the Application
Apache web server and MySQL services should be running in the XAMPP control panel. In the browser run localhost/modal_login. You will see the home page displayed.
Click on Login from the menu. The login modal should be displayed. Enter email id as 'test@test.com', password as '123' and submit.
You should be able to login successfully and see the home page. Also, you should see that the user name is displayed in the top right corner along with the Logout link.
Also, try to login with an incorrect email/password, you should see the modal displayed again with an error message displayed on top saying "Incorrect Email id/Password".
Download Source Code
Click on the Download button below to download the source code.
Conclusion
We have seen how you can develop a modal login form with a simple menu. This is the simplest menu and the form. In the real project, there could be many other things you have to code for. I made it very simple for you, you can always improve it. I hope it will be useful to you.
Post a Comment