Registration and Login System in PHP and MYSQL | source code download

In the previous post we saw how to create responsive registration and login form using bootstrap, if you haven't read this post yet, please read that post first, after that we will move on. today we will verify this registration and login form after that store the data in the MySQL database.

let's start

First of all, create a new file like the below file structure.

Responsive Registration and Login form in php with mysqli source code
file Structure

After creating this file structure then follow my instruction. Although in the previous post, we had created the registration and login form in how to make responsive registration and login form, let us create it again with the help of copy-paste.

To create the registration form page, open the register.php file in any text editor like a sublime text editor and copy and paste the code given below.

register.php:

<!doctype html>
  <html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <!-- Sweet Alert CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
    <title>Bootstrap Registration Form</title>
  </head>
  <body>
    <div class="container-fluid my-3">
      <div class="row justify-content-center">
        <div class="col-lg-4">
          <div class="card bg-dark text-light">
            <h2 class="card-title text-light mt-3" align="center">Register</h2>
            <p class="card-text" align="center"> Please Register if you want Access our Webiste</p>
            <hr class=" border position-relative " style="width: 70%; align-self: center; margin: 0px;">
            <div class="card-body">
              <form class="row g-3 mt-3 needs-validation" action="register.php" method="post" novalidate>
                <div class="col-md-6">
                  <label for="enterfirstname" class="form-label">First name</label>
                  <input type="text" class="form-control rounded-pill" name="firstname" id="enterfirstname" value="" required>
                  <div class="invalid-feedback">
                    Enter First Name !
                  </div>
                </div>
                <div class="col-md-6">
                  <label for="enterlastname" class="form-label">Last name</label>
                  <input type="text" class="form-control rounded-pill" name="lastname" id="enterlastname" value="" required>
                  <div class="invalid-feedback">
                    Enter Last Name !
                  </div>
                </div>
                <label for="selectusername" class="form-label">Username</label>
                <div class="input-group has-validation">
                  <input type="text" class="form-control rounded-pill" name="username" id="selectusername" aria-describedby="inputGroupPrepend" required>
                  <div class="invalid-feedback">
                    Please Create a uniq username.
                  </div>
                </div>
                <label for="enteremail" class="form-label">Email</label>
                <div class="input-group has-validation">
                  <input type="email" class="form-control rounded-pill" name="email" id="enteremail" aria-describedby="inputGroupPrepend" required>
                  <div class="invalid-feedback">
                    Please Enter Valid Email.
                  </div>
                </div>
                <label for="enterphone" class="form-label">Mobile Number</label>
                <div class="input-group has-validation">
                  <input type="numbers" class="form-control rounded-pill" name="mobile" id="enterphone" placeholder="Enter 10 digit" aria-describedby="inputGroupPrepend" required>
                  <div class="invalid-feedback">
                    Please Enter Your Contact Number.
                  </div>
                </div>
                <div class="col-md-3">
                  <label for="selectcity" class="form-label">City</label>
                  <input type="text" class="form-control rounded-pill" name="city" id="selectcity" required>
                  <div class="invalid-feedback">
                    Please provide a valid city.
                  </div>
                </div>
                <div class="col-md-6">
                  <label for="validationCustom04" class="form-label">State</label>
                  <select class="form-select rounded-pill" name="state" id="validationCustom04" required>
                    <option selected disabled value="">Choose...</option>
                    <option value="chattisgarh">Chhattisgrah</option>
                  </select>
                  <div class="invalid-feedback">
                    Please select a valid state.
                  </div>
                </div>
                <div class="col-md-3">
                  <label for="zip1" class="form-label">Zip</label>
                  <input type="text" class="form-control rounded-pill" name="zip" id="zip1" required>
                  <div class="invalid-feedback">
                    Please provide a valid zip.
                  </div>
                </div>
                <label for="validationPassword">Password</label>
                <input type="password" class="form-control rounded-pill" id="validationPassword" minlength="8" name="password" placeholder="Password" value="" required>
                <label for="cpass">Confirm-Password</label>
                <input type="password" class="form-control rounded-pill" id="cpass" minlength="8" name="cpassword" placeholder="Confirm-Password" value="" required>
                <div class="col-12">
                  <div class="form-check">
                    <input class="form-check-input rounded-pill" type="checkbox" value="" id="invalidCheck" required>
                    <label class="form-check-label" for="invalidCheck">
                      Agree to terms and conditions
                    </label>
                    <div class="invalid-feedback">
                      You must agree before submitting.
                    </div>
                  </div>
                </div>
                <div class="col-md-12 text-center ">
                  <button class="btn btn-secondary" title="Submit Your Form" aria-label="Left Align" name="reg_user" type="submit"> <span class="fa fa-user-plus" aria-hidden="true"></span> Register</button>
                </div>
                <span class="extra-line text-center">
                  <span>Already have an account?</span>
                  <a href="login.php">Login</a>
                  <!--  actually this is login.php link but i use codepen taged login.php -->
                </span>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- Optional JavaScript; choose one of the two! -->
    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="js/custom.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <!-- Option 2: Separate Popper and Bootstrap JS -->
<!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
-->
</body>
</html>

We will do the same thing in creating the login form page.

To create a login form, open the login.php file and copy-paste the code below.

login.php:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <title>Bootstrap Login Form</title>
  </head>
  <body>
   <div class="container-fluid">
<div class="row justify-content-center">
	<div class="col-lg-4 mt-5">
		<div class="card bg-dark text-light">
				<h2 class="card-title text-light mt-3" align="center">Login</h2>
				<p class="card-text" align="center"> Please Login if you want Access our Webiste</p>
				<hr class=" border position-relative " style="width: 70%; align-self: center; margin: 0px;">
				<div class="card-body">
				<form class="row g-3 mt-0 needs-validation" action="login.php" method="post" novalidate>

            <label for="enteremail" class="form-label">Email</label>
            <div class="input-group has-validation">                          
              <input type="email" class="form-control rounded-pill" name="email" id="enteremail"  aria-describedby="inputGroupPrepend" required>
              <div class="invalid-feedback">
                Please Enter Valid Email.
              </div>
            </div>          

            <label for="password1" class="form-label">Password</label>
            <div class="input-group has-validation">                          
              <input type="password" class="form-control rounded-pill" name="password" id="password1"  aria-describedby="inputGroupPrepend" required>
              <div class="invalid-feedback">
                Enter Password
              </div>
            </div> 
            <div class="col-6">
              <div class="form-check">
                <input class="form-check-input" name="remeberme" type="checkbox" value="" id="invalidCheck">
                <label class="form-check-label" for="invalidCheck">
                  Remember Me
                </label>                
              </div>
            </div>
             <div class="col-6" align="right">
              <a href="recover_email.php">Forgot Password</a>
            </div>
            <div class="col-md-12 text-center ">
              <button class="btn btn-secondary" name="log_user" title="Submit Your Form" aria-label="Left Align" type="submit"> <span class="fa fa-user" aria-hidden="true"></span> Login</button>
            </div>
            <span class="extra-line text-center">
              <span>Don't have an account ?</span>
              <a href="register.php">Register</a>
            </span>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
    <!-- Optional JavaScript; choose one of the two! -->
    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
    -->
  </body>
</html>

Here we have used Bootstrap to design the login and registration page so we don't need custom CSS.

Now turn on your localhost server and go to any browser and paste the below URL in the URL Bar.

localhost\register-form\register.php

If you have followed the instructions correctly, then congratulations your responsive registration and login form are completely ready. This form is going to look like this in the browser

The full code of the responsive registration and login form page is -

See the Pen Untitled by Ramkrishna Sahu (@ramkrishna-sahu) on CodePen.

Validate this form later, first create a database for this form and store its data in this database after registering the users.

Create a database for registration and login forms

In this section, we will be working on our database design and user authentication (registration and login). Go to http://localhost/phpmyadmin/ and create a database named registration-login-system. In this database, create a table named users which will store all the details of the registered users.

You can create these tables using these SQL commands.

users:


CREATE TABLE `registration-login-system`.`users` (`id` INT(11) NOT NULL , `first_name` VARCHAR(100) NOT NULL , `last_name` VARCHAR(100) NOT NULL , `username` VARCHAR(100) NOT NULL , `email` VARCHAR(100) NOT NULL , `mobile` VARCHAR(100) NOT NULL , `city` VARCHAR(100) NOT NULL , `state` VARCHAR(100) NOT NULL , `zip` VARCHAR(100) NOT NULL , `token` VARCHAR(100) NOT NULL , `password` VARCHAR(100) NOT NULL ) ENGINE = InnoDB;

You can run these scripts by using the SQL command prompt or PHPMyAdmin. 

On PHPMyAdmin, click/select the database you want these tables created under (in this case complete-blog-php), then click on the SQL tab on the navbar somewhere at the top of the page.

If you see any SQL script in the space below, remove it and paste the script above into the space provided and click 'Go' to create the tables.

If you chose to manually create these tables instead, remember to make the id field on the users table a primary key and auto increment.

After creating the database let's create a config.php file to connect to it.

In config.php, let's add code to connect our application to the database. After adding the code, our config.php file will look like this:

<?php 
  session_start();
  // connect to database
  $conn = mysqli_connect("localhost", "root", "", "registration-login-system");
  if (!$conn) {
  die("Error connecting to database: " . mysqli_connect_error());
  }
?>;

This returns a database connectivity object $conn which we can use in our entire application for querying the database.

Now create a file named logic.php in the register-form folder. This file is going to hold the logic of our registration and login form, under this we will keep all our PHP logic. This first logic is for user registration.

Let's create it in our root folder and put this code inside it -

logic.php:

<?php 
//variable Declaration
/*------------------------------------
// Register Users (register.php)
------------------------------------*/

if (isset($_POST['reg_user'])) {

$firstname = mysqli_real_escape_string($conn, $_POST['firstname']);
$lastname = mysqli_real_escape_string($conn, $_POST['lastname']); 
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$state = mysqli_real_escape_string($conn, $_POST['state']);
$zip = mysqli_real_escape_string($conn, $_POST['zip']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']);

if ($password != $cpassword) { //Check password and confirm password is same or not.
	echo '<script type="text/javascript">';
	echo 'setTimeout(function () { swal("incorrect!","The two password are not matching","warning");';
	echo '}, 100);</script>';	
}

$token = bin2hex(random_bytes(20));
//email check query if exists
$email_check = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
$run_query = mysqli_query($conn, $email_check);
$users = mysqli_fetch_assoc($run_query);
// Check if users Exsist
if ($users) {
 if ($users['username'] === $username ) {
	echo '<script type="text/javascript">';
	echo 'setTimeout(function () { swal("Warning!","Username already exists","warning");';
	echo '}, 100);</script>';
}
if ($users['email'] === $email) {
	echo '<script type="text/javascript">';
	echo 'setTimeout(function () { swal("Warning!","Email already exists","warning");';
	echo '}, 100);</script>';
}
 }else{
//insert Data if there are no errors
$pass = password_hash($password, PASSWORD_BCRYPT);			
$iquery = "INSERT INTO users(first_name, last_name, username, email, mobile, city, state, zip, token, password) VALUES ('$firstname', '$lastname', '$username', '$email', '$mobile', '$city', '$state', '$zip', '$token', '$pass')";
$insert = mysqli_query($conn, $iquery);
if ($insert) {							
// get id of created user
	$reg_user_id = mysqli_insert_id($conn);
	echo '<script type="text/javascript">';
	echo 'setTimeout(function () { swal("Registration Successfull!","After 3 seconds, you will be redirected to the login page","success");';
	echo '}, 100);</script>';
}else{

echo '<script type="text/javascript">';
	echo 'setTimeout(function () { swal("Not inserted!","Registration failed","error");';
	echo '}, 100);</script>';
  }
 }
}

After adding this code, we need to include this file in the register and login page.

Open the register.php and login.php pages and paste these two line codes in the first line.

<?php include ("config.php") ?>
<?php include ("logic.php") ?>

Once check whether the register page is working properly or not. Go to http://localhost/regiter-form/register.php and fill out the form. After filling out the form and after clicking on the register button, check your database, the data proper will have arrived in the database.

We have used a sweetalert of javascript instead of a SESSION variable to show the success and error messages. You can ignore sweetalert and use the $_SESSION global variable instead.

Login System in PHP MYSQL

Well, the logic of the registration form has been completed, and now we have to work on the login form.

See, the basic concept of logic is that if a registered user wants to log in by entering his correct email and password, then he can log in because he had already registered (Create Account) by entering his email whose data is in the database. If I have a store then we will allow it to log in properly and redirect it to our welcome page.

And if a user is neither registered (not created an account) nor has its record stored in the database, then we will not allow such a user to log in and redirect to the registration page to register (create an account) and a message will show that you have not created an account yet.

So let's get started. Open logic.php again and add this code below the commented login users.

logic.php:


/*------------------------------------
// Login Users (login.php)
------------------------------------*/

if (isset($_POST['log_user'])) {
	$email = mysqli_real_escape_string($conn, $_POST['email']);
	$password = mysqli_real_escape_string($conn, $_POST['password']);
	if (empty($email)) {
		array_push($errors, "email can not be blank");
	}

// Check Email/Username exists Or no
	$search_email = "SELECT * FROM users WHERE email = '$email' || password = '$password' ";
	$run_query = mysqli_query($conn, $search_email);
	$emailcount = mysqli_num_rows($run_query);

	if ($emailcount) {

		$email_pass = mysqli_fetch_assoc($run_query);
		$db_pass = $email_pass['password'];
		$reg_user_id = $email_pass['id'];
		$_SESSION['user'] = $email_pass['username'];
		$pass_decode = password_verify($password, $db_pass);
		if ($pass_decode) {
// put logged in user into session array
			echo '<script type="text/javascript">';
			echo 'setTimeout(function () { swal("Login Successsfully!"," you will redirect Dashboard Page","success");';
			echo '}, 100);</script>';
// Check user click or not click Remember me Checkbox Button
			if (isset($_POST['remeberme'])) { //if user click or checked checkbox then set cookies
				setcookie('emailcookies',$email,time()+900);
				setcookie('passwordcookies',$password,time()+900);
			}
// redirect to welcome page
				header('location: index.php');				
				exit(0);
	}else{
		echo '<script type="text/javascript">';
		echo 'setTimeout(function () { swal("Errors!","Password Incorrect","error");';
		echo '}, 100);</script>';
	}
	}else{
		echo '<script type="text/javascript">';
		echo 'setTimeout(function () { swal("Warning!","Email not found","warning");';
		echo '}, 100);</script>';				
	}
}
?>

after entering this code save all files and go to this URL http://localhost/regiter-form/register.php 

First of all register correctly, after registering, check the database whether the data is being stored correctly in the database or not, if the data is being stored then go to the login page and log in.

Once by giving wrong information, you can also check the performance of the form, you can also do the validation of the form well with the help of PHP.

If the login is done successfully then -  Not Found The requested URL was not found on this server. You must be facing some type of error, this error is coming because till now we have not created any index page, this index page will be our welcome page or home page.

Now Let's create an index.php page inside the root folder and put this code inside it.

index.php:


<?php 
include ("config.php");
include ("logic.php");
?>
<!doctype html>
  <html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <!-- Sweet Alert CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
    <title>Welcome Page</title>
  </head>
  <body>
    <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">Logo</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="collapsibleNavbar">
          <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
            
            <li class="nav-item">
              <a class="nav-link btn btn-success me-2" href="register.php">Register</a>
            </li>
            <li class="nav-item">
              <a class="nav-link btn btn-primary me-2" href="login.php">Log in</a>
            </li>    
          </ul>
        </div>
      </div>
    </nav>
      <div class="container-fluid my-3">
        <div class="row justify-content-center">
          <div class="col-lg-8">
            <?php if(isset($_SESSION['user'])):
              echo '<h1> Welcome <span class="text-info"> ' . $_SESSION['user'] . '</span></h1>';
              echo '<a href="logout.php">Logout </a>';
             endif ?>               
             </div>
           </div>
         </div>      
    <!-- Optional JavaScript; choose one of the two! -->
    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="js/custom.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <!-- Option 2: Separate Popper and Bootstrap JS -->
<!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
-->
</body>
</html>

Refresh the browser now the error will be gone.

Logout System in PHP

If the user logins once, then obviously he will also log out, so we will also have to create a logout page, so that the user can log out.

We don't have to do much to log out, we just have to destroy the session and send it to the login page to log in again.

Create a logout.php page inside the root folder and just put this code inside it.

logout.php:

<?php 
session_start();
session_destroy();
session_unset();
unset($_SESSION['user']);
header('location: login.php');
?>

In logout, we have destroyed the session and unset where we set the session now if the user is logged out once then he cannot log in until he login again. In this way, our registration and login system ends.

Conclusion:

Today we learned about registration and login system in PHP and MySQL. Sorry for this article being long. Hope this article has been very useful for you. If you liked this article then do not forget to like and subscribe to our newsletter and not forget to share it with your friends.

In the next tutorial, we will see 👉 How to Add Remember Me Functionality to Login Page using PHP.

if any questions related to this article please tell us in the comment box.

If you want, you can download its source code for free from the download button below.

Registration & Login System in PHP And MYSQL Source Code Download

Source Code Free Source Code Download Download Now

Post a Comment

0 Comments

Youtube Channel Image
Rkonline | Learn Programming Language Subscribe To watch more Blogging Tutorials
Subscribe