In this tutorial, we will create a simple PHP Login System Using MySQL And JQuery AJAX.
Simple PHP Login System Using MySQL And JQuery AJAX
Requirements
- Knowledge of HTML, CSS, PHP, and MySQL, AJAX, BOOTSTRAP for creating the login system.
- Text Editor – For writing the code. We can use any text editor such as VisualCode, Notepad, Notepad++, Sublime, etc.
- XAMPP – XAMPP is a cross-platform software, which stands for Cross-platform(X) Apache server (A), MySQL (M), PHP (P), Perl (P). XAMPP is a complete software package, so, we don’t need to install all these separately.
Read more:- Secure Login System with PHP and MySQL
File need
Now, we will create five files here for the login system.
- db.php – Connection file contains the connection code for database connectivity
- header.php – which contains all the stylesheet link
- register_login.php – Login page +Register page.
- auth.php – This file validates the form data with the database which is submitted by the user.
- home.php – the user redirects after login.
- fetch.js – contains all the ajax code
- login_reg_insert.php – PHP code of login and register
Save all these files in the htdocs folder inside the Xampp installation folder. The detailed description and code for these files are discussed below.
This Php tutorial will handle login functionality, Creating login and register form using Bootstrap, CSS, Ajax, Jquery, and MySQL for validating user records from the database
In this section, we’ll build a registration system that allows users to create a new account by filling out a web form. But, first, we need to create a table that will hold all the user data.
Step 1: Creating the Database Table
Execute the following SQL query to create the users table in your MySQL database.
Database name should be loginsystem.
As you can see, I have passed below MySQL database parameters.
--
-- Database: `loginsystem`
--
CREATE TABLE `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT,
`gender` varchar(255) NOT NULL,
`email` varchar(255) DEFAULT NULL,
`phone` varchar(255) DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`uploaded_on` datetime DEFAULT NULL,
PRIMARY KEY (id)
)
--
Step 2: Creating the DB File
After creating the table, we need to create a PHP script in order to connect to the MySQL database server. Create a file named “db.php” and put the following code inside it.
<?php
$connect= mysqli_connect("localhost", "root", "", "loginsystem");
// Check connection
if($connect === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
Servername
: localhostUsername
: rootPassword
:Dbname
:loginsystem
Step 3: Creating the header file
Create another PHP file “header.php” and put the following example code in it.
We include header.php in register_login.php and home.php.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" ></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
Step 4: Creating the Registration file
Let’s create another PHP file “register_login.php” and put the following example code in it.
This script will also generate errors if a user tries to submit the form without entering any value, or if the username or email entered by the user is already taken by another user.
In this login system, you can also see the password on registration when you click to show the password
I have defined a div(#error
) which will use to show error message on the wrong credential supplied.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login System</title>
<!-- Mobile Specific Metas -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- Font-->
<?php include("header.php");?>
<!-- Main Style Css -->
<link rel="stylesheet" href="css/login_style.css"/>
</head>
<body class="form-v2 page-content">
<div class="form-v2-content">
<div class="form-detail " >
<div class="mb-5 mt-3 " style="text-align: center;">
<div class="btn-group " role="group" aria-label="Basic example">
<button type="button" class="btn btn-danger" id="register">Register</button>
<button type="button" class="btn btn-primary" id="login">Login</button>
</div>
</div>
<form id="register_form" name="form1" method="post" >
<div class="alert " id="error" role="alert" style="display:none;">
<div><a href="#" class="close" data-dismiss="alert" aria-label="close">X</a></div>
<div class="error_show" id="error_show1"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" id="name" placeholder="FullName" name="name" >
</div>
<div class="form-group">
<input type="username" class="form-control" id="username" placeholder="username" name="username" >
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Email@email.com" name="email" >
</div>
<div class="form-group">
<input type="text" class="form-control" id="phone" placeholder="Phone Number " name="phone">
</div>
<input type="password" class="form-control" id="password" placeholder="Password" name="password">
<div class="form-group ">
<div class="form-check">
<input class="form-check-input" type="checkbox" id='check' style="width: 3%; -webkit-appearance: checkbox;">
<label class="form-check-label" for="gridCheck">
Show Password
</label>
</div>
</div>
<input type="password" class="form-control" id="confirm_password" placeholder="confirm_password" name="confirm_password">
<div class="mb-3"></div>
<input type="button" name="save" class="btn btn-primary" value="Register" id="butsave">
</form>
<form id="login_form" name="form1" method="post" style="display:none;">
<div class="alert " id="error1" role="alert" style="display:none;">
<div><a href="#" class="close" data-dismiss="alert" aria-label="close">X</a></div>
<div class="error_show" id="error_show12"></div>
</div>
<div class="form-group">
<label for="pwd">Username:</label>
<input type="username" class="form-control" id="email_log" placeholder="Email" name="username" >
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="password_log" placeholder="Password" name="password">
</div>
<input type="button" name="save" class="btn btn-primary" value="Login" id="butlogin">
</form>
</div>
</div>
</body>
</html>
<script src="js/fetch.js"></script>
The output of the Registration + login form page example
Step 5: Creating the PHP file for the login system
Let’s create another PHP file “login_reg_insert.php” and put the following example code in it.
In the Php file there are 2 php code :
1st to insert data when register and 2nd for login
- Checks if the username or email present in the database or not, if the present error will show.
- On registration, the password is encrypted using Php
md5()
method.
<?php
include("db.php");
session_start();
if($_POST['type']==1){
$name=$_POST['name'];
$email=$_POST['email'];
$username=$_POST['username'];
$phone=$_POST['phone'];
$password=$_POST['password'];
if(!empty($name) && !empty($email) && !empty($username) && !empty($phone) && !empty($password)){
$duplicate=mysqli_query($connect,"select * from users where email='$email'");
$duplicate1=mysqli_query($connect,"select * from users where username='$username'");
if (mysqli_num_rows($duplicate)>0)
{
echo json_encode(array("statusCode"=>201));
}
else if (mysqli_num_rows($duplicate1)>0)
{
echo json_encode(array("statusCode"=>202));
}
else{
$sql = "INSERT INTO `users`( `name`, `email`, `phone`, `password`,`username`,`uploaded_on`)
VALUES ('$name','$email','$phone','".md5($password)."', '$username',NOW())";
if (mysqli_query($connect, $sql)) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>203));
}
}
mysqli_close($connect);
}
else{
echo json_encode(array("statusCode"=>204));
}
}
if($_POST['type']==2){
$username=$_POST['username'];
$password=$_POST['password'];
$check=mysqli_query($connect,"select * from users where username='$username' AND password='".md5($password)."'");
if (mysqli_num_rows($check)>0)
{
$_SESSION['username']=$username;
echo json_encode(array("statusCode"=>200));
}
else{
echo json_encode(array("statusCode"=>201));
}
mysqli_close($connect);
}
?>
Step 6: Creating the ajax file for the login system
Let’s create another PHP file “fetch.php” and put the following example code in it.
In this file the validation is done
- The input field is not empty
- Password validation
- Contain Alphabets, special Character, numeric Character
- Contain almost 7 character
- Confirm Password is same as Password
- Email validation
$(document).ready(function() {
$('#check').click(function() {
if ($('#password').attr('type') == 'text') {
$('#password').attr('type', 'password');
} else {
$('#password').attr('type', 'text');
}
});
$('#login').on('click', function() {
$("#login_form").show();
$("#register_form").hide();
});
$('#register').on('click', function() {
$("#register_form").show();
$("#login_form").hide();
});
// register
$('#butsave').on('click', function() {
var v = document.getElementById("error");
emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
var name = $('#name').val();
var email = $('#email').val();
var username = $('#username').val();
var phone = $('#phone').val();
var password = $('#password').val();
var confirm_password = $('#confirm_password').val();
setTimeout(function() { $("#error").fadeOut(1000); }, 5000);
if(name=="" && email=="" && phone=="" && password=="" ){
$("#error").show();
$('#error_show1').html('Please fill all the field!');
v.className += " alert-danger";
}
else if(! emailReg.test( email ) ){
$("#error").show();
$('#error_show1').html('Email is not valid!');
v.className += " alert-danger";
}
else if( password != confirm_password ){
$("#error").show();
$('#error_show1').html('Password is not same!');
v.className += " alert-danger";
}
else if( !password.match(/([a-zA-Z])/) && password.match(/([0-9])/)){
$("#error").show();
$('#error_show1').html('Please use Both uppercase and lowercase!');
v.className += " alert-danger";
}
else if( !password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)){
$("#error").show();
$('#error_show1').html('Please use special character!');
v.className += " alert-danger";
}
else if( !password.length > 7){
$("#error").show();
$('#error_show1').html('Please use more than 8 Character!');
v.className += " alert-danger";
}
else{
$.ajax({
url: "login_reg_insert.php",
type: "POST",
data: {
type: 1,
name: name,
email: email,
username: username,
phone: phone,
password: password
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#error").show();
$('#error_show1').html('Registration successfull Go to Login !');
v.className += " alert-success";
$('#register_form').val('');
}
else if(dataResult.statusCode==201){
$("#error").show();
$('#error_show1').html('Email ID already exists !');
v.className += " alert-danger";
}
else if(dataResult.statusCode==202){
$("#error").show();
$('#error_show1').html('Username already exists !');
v.className += " alert-danger";
}
else if(dataResult.statusCode==203){
$("#error").show();
$('#error_show1').html('Not Inserted !');
v.className += " alert-danger";
}
else if(dataResult.statusCode==204){
$("#error").show();
$('#error_show1').html('Please fill all the field!');
v.className += " alert-danger";
}
}
});
}
});
// login
$('#butlogin').on('click', function() {
$("#error1").hide();
var v = document.getElementById("error1");
var username = $('#email_log').val();
var password = $('#password_log').val();
setTimeout(function() { $("#error1").fadeOut(1000); }, 3000);
if(username=="" && password=="" ){
$("#error1").show();
$('#error_show12').html('Please fill all the field!');
v.className += " alert-danger";
}
else {
$.ajax({
url: "login_reg_insert.php",
type: "POST",
data: {
type:2,
username: username,
password: password
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
location.href = "home.php";
}
else if(dataResult.statusCode==201){
$("#error1").show();
$('#error_show12').html('Invalid EmailId or Password !');
v.className += " alert-danger";
}
}
});
}
});
});
Step 7: Creating the css file for the login system
Let’s create another PHP file “login_style.css” and put the following example code in it.
body {
margin: 0;
}
.page-content {
width: 100%;
margin: 0 auto;
background-image: -moz-linear-gradient( 136deg, rgb(224,195,252) 0%, rgb(142,197,252) 100%);
background-image: -webkit-linear-gradient( 136deg, rgb(224,195,252) 0%, rgb(142,197,252) 100%);
background-image: -ms-linear-gradient( 136deg, rgb(224,195,252) 0%, rgb(142,197,252) 100%);
display: flex;
display: -webkit-flex;
justify-content: center;
-o-justify-content: center;
-ms-justify-content: center;
-moz-justify-content: center;
-webkit-justify-content: center;
align-items: center;
-o-align-items: center;
-ms-align-items: center;
-moz-align-items: center;
-webkit-align-items: center;
}
.form-v2-content {
background: #fff;
width: 851px;
border-radius: 15px;
-o-border-radius: 15px;
-ms-border-radius: 15px;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
margin: 5% 0;
position: relative;
display: flex;
display: -webkit-flex;
}
.form-v2-content .form-detail {
padding: 20px 40px 20px 40px;
position: relative;
width: 100%;
}
.form-v2-content .form-detail h2 {
font-family: 'Roboto', sans-serif;
font-weight: 700;
color: #333;
font-size: 28px;
position: relative;
padding: 6px 0 0;
margin-bottom: 25px;
}
.form-v2-content .form-row {
width: 100%;
position: relative;
}
.form-v2-content .form-detail label {
font-family: 'Roboto', sans-serif;
font-weight: 400;
font-size: 16px;
color: #666;
display: block;
margin-bottom: 11px;
}
.form-v2-content .form-detail .form-row label#valid {
position: absolute;
right: 20px;
top: 50%;
transform: translateY(-50%);
-o-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
width: 14px;
height: 14px;
border-radius: 50%;
-o-border-radius: 50%;
-ms-border-radius: 50%;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
background: #53c83c;
}
.form-v2-content .form-detail .form-row label#valid::after {
content: "";
position: absolute;
left: 5px;
top: 1px;
width: 3px;
height: 8px;
border: 1px solid #fff;
border-width: 0 2px 2px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
-moz-transform: rotate(45deg);
transform: rotate(45deg);
}
.form-v2-content .form-detail .form-row label.error {
padding-left: 0;
margin-left: 0;
display: block;
position: absolute;
bottom: -10px;
width: 100%;
background: none;
color: red;
}
.form-v2-content .form-detail .form-row label.error::after {
content: "\f343";
font-family: "LineAwesome";
position: absolute;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
right: 10px;
top: -31px;
color: red;
font-size: 18px;
font-weight: 900;
}
.form-v2-content .form-detail .input-text {
margin-bottom: 27px;
}
.form-v2-content .form-detail input {
width:100%;
padding: 25.5px 15px;
border: 1px solid #e5e5e5;
border-radius: 5px;
-o-border-radius: 5px;
-ms-border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
appearance: unset;
-moz-appearance: unset;
-webkit-appearance: unset;
-o-appearance: unset;
-ms-appearance: unset;
outline: none;
-moz-outline: none;
-webkit-outline: none;
-o-outline: none;
-ms-outline: none;
font-family: 'Roboto', sans-serif;
font-size: 16px;
color: #333;
}
.form-v2-content .form-detail .form-row input:focus {
border: 1px solid #53c83c;
}
.form-v2-content .form-detail input[type="radio"] {
outline: none;
-moz-outline: none;
-webkit-outline: none;
-o-outline: none;
-ms-outline: none;
-o-appearance: none;
-ms-appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
display: inline-block;
width: 20px;
height: 20px;
padding: 4px;
background-clip: content-box;
border: 1px solid #e5e5e5;
background-color: #fff;
border-radius: 50%;
-o-border-radius: 50%;
-ms-border-radius: 50%;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
cursor: pointer;
float: left;
margin-top: 0;
}
.form-v2-content .form-detail .form-checkbox {
width: 80%;
margin-top: -17px;
position: relative;
}
.form-v2-content .form-detail .form-checkbox input {
position: absolute;
opacity: 0;
}
.form-v2-content .form-detail .form-checkbox .checkmark {
position: absolute;
top: 20px;
left: 0;
height: 15px;
width: 15px;
border: 1px solid #ccc;
cursor: pointer;
}
.form-v2-content .form-detail .form-checkbox .checkmark::after {
content: "";
position: absolute;
left: 5px;
top: 1px;
width: 3px;
height: 8px;
border: 1px solid #385cb9;
border-width: 0 2px 2px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
-moz-transform: rotate(45deg);
transform: rotate(45deg);
display: none;
}
.form-v2-content .form-detail .form-checkbox input:checked ~ .checkmark::after {
display: block;
}
.form-v2-content .form-detail .form-checkbox p {
margin-left: 35px;
color: #666;
font-size: 16px;
font-weight: 400;
font-family: 'Roboto', sans-serif;
line-height: 1.67;
}
.form-v2-content .form-detail .form-checkbox a {
font-weight: 500;
color: #385cb9;
text-decoration: underline;
}
.form-v2-content .form-detail .register {
background: #3b63ca;
border-radius: 6px;
-o-border-radius: 6px;
-ms-border-radius: 6px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
width: 160px;
border: none;
margin: 6px 0 50px 0px;
cursor: pointer;
font-family: 'Roboto', sans-serif;
color: #fff;
font-weight: 500;
font-size: 16px;
}
.form-v2-content .form-detail .register:hover {
background: #3356b0;
}
.form-v2-content .form-detail .form-row-last input {
padding: 15.5px;
}
input::-webkit-input-placeholder { /* Chrome/Opera/Safari */
color: #999;
font-size: 14px;
}
input::-moz-placeholder { /* Firefox 19+ */
color: #999;
font-size: 14px;
}
input:-ms-input-placeholder { /* IE 10+ */
color: #999;
font-size: 14px;
}
input:-moz-placeholder { /* Firefox 18- */
color: #999;
font-size: 14px;
}
/* Responsive */
@media screen and (max-width: 991px) {
.form-v2-content {
margin: 180px 20px;
flex-direction: column;
-o-flex-direction: column;
-ms-flex-direction: column;
-moz-flex-direction: column;
-webkit-flex-direction: column;
}
.form-v2-content .form-detail {
padding: 30px 20px 30px 20px;
width: auto;
}
.form-v2-content .form-detail .form-row input {
width: 95%;
}
.form-v2-content .form-detail .form-checkbox {
width: 100%;
}
}
@media screen and (max-width: 575px) {
.form-v2-content .form-detail .form-row input {
width: 89.5%;
}
}
Step 8: Creating the Welcome Page
Let’s create another PHP file “home.php” and put the following example code in it. where the user is redirected after successful login.
<?php include('auth.php');?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<?php include('header.php');?>
</head>
<body>
<div class="container text-center p-5 m-5">
<div class=" p-5 display-1 text-center" style="font-family: 'Sigmar One', cursive;">Hello, Sir</div>
<div class=" p-5 display-4 text-center" style="font-family: 'Sigmar One', cursive;">How are you</div>
<div class="btn btn-primary btn-outline-primary rounded-pill btn-lg font-weight-bolder">
<a href="logout.php" class="text-white text-center" >
<p>LOGOUT</p>
</a>
</div>
</div>
</body>
</html>
The output of the above example
Step 9: Creating the Logout file
Now, let’s create a “logout.php” file. When the user clicks on the logout button, the script inside this file destroys the session and redirect the user back to the login page.
<?php
session_start();
// Destroying All Sessions
if(session_destroy())
{
// Redirecting To Home Page
header("Location: register_login.php");
}
?>
Step 10: Creating the Authentication file
Now, let’s create an “auth.php” file. Check if the user is logged in or not. If not logged in, then the user will be redirected to “register_login.php” automatically.
<?php
session_start();
if(!isset($_SESSION["username"])){
header("Location: register_login.php");
exit(); }
?>
Related: –