Registration and login form in PHP and MYSQL


We visit many websites daily for services and learning. The data security holds by the restrictions and based on the passwords. In this tutorial, we will create a registration and login form in PHP with an MYSQL database. The registration form will be used as a signup to take data from the users and the login form will be used to access the restricted page. If you want to create a registration and login system for your PHP website then you should follow the complete tutorial. In this tutorial, we will design a responsive form using Bootstrap. As you know, the bootstrap is one of the best frameworks for website designing. We will use bootstrap CSS classed and will make responsive registration and login form. In the current time, technology is updating daily. The responsive website gets more attractive to the users.

Lets, create a Registration and login form in PHP –

Registration form in PHP with MYSQL database – 

The registration form is a form to get data from the visitors (users). The registration form is known as a Signup form. We use a registration form for user registration or you can use it as student registration.

Let’s make the registration form in PHP

First of all, create a database table on your PHPMYADMIN panel.


CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fname` varchar(255) DEFAULT NULL,
  `lname` varchar(255) DEFAULT NULL,
  `username` varchar(300) DEFAULT NULL,
  `email` varchar(300) DEFAULT NULL,
  `password` varchar(300) DEFAULT NULL,
  `date` date NOT NULL,
   PRIMARY KEY (`id`)
); 

In the table above, we have taken users of the table name. In the users table, we have created many fields.

Execute the query above on your PHPMYADMIN panel.

The data table has been created into MYSQL.

Now, we will create PHP scripts for the registration form.

Create connection file for MYSQL database connection.–

The connection file will be used to connect PHP scripts to the MYSQL database. This is a connection between the users to the database and the browser completes the request from the users.

Create a connection file with the name -    config.php

config.php


<?php
session_start();
$dbHost = 'localhost';
$dbName = 'tutorials';
$dbUsername = 'root';
$dbPassword = '';
$dbc= mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName); 
?>

In the connection file above, we have started the session for whole pages because we will use the session to login and access the entire restricted page by the login form. This is known as the login system in PHP.

In the code above, we have created variables for database connection and used the mysqli_connect() function for the database connection to the registration and login form.

The connection file will be used for whole pages of the website.

Now, we will use bootstrap and additional CSS to design a signup form.

 We will use PHP code in the same registration file.

Let's understand the part of this signup or registration form.

  1. Bootstrap – Bootstrap is one of the best HTML and CSS framework which is used to design a responsive website. You can download bootstrap or link direct in your HTML <head> tag . As you know, the bootstrap is a readymade platform. We will make responsive registration and login form in PHP with MYSQL. We will use bootstrap classes in the registration and login form.

  2.  Registration form in PHP – After designing the registration form with bootstrap, we will create PHP code inside the same signup file (Registration file ).

In the registration form, the data should be inserted in the correct. We will make validations by PHP on button submit. The validations are very important to ensure the correct form of data is going to be inserted into the database.

Validations for registration form fields –

1 Validation form minimum value in the input box –

This validation validates that the user should enter the minimum value in the input box. You can set the minimum value for the input box.

Example -


if(strlen($fname)<3){ // Minimum 
      $error[] = 'Please enter First Name using 3 charaters atleast.';
        }

2. Maximum value in the input box –

This is another validation of the input box that restricts users to enter the value in the registration form below a limit.

Example –


if(strlen($fname)>20){  // Max 
      $error[] = 'First Name: Max length 20 Characters Not allowed';
        }

3. Registration form fields validation with regular expression-

Regular expression helps to validate the correct form of data. In the registration form, we use regular expressions according to the situation –

Example-

Username- The username should not be started with digits.

The username should not be contained white space at the starting and between the characters or digits.

  This type of situation handles by the regular expression –


if(!preg_match("/^^[^0-9][a-z0-9]+([_-]?[a-z0-9])*$/", $username)){
            $erro5r[] = 'Invalid Entry for Username. Enter lowercase letters without any space and No number at the start- Eg - myusername, okuniqueuser or myusername123';

In the code above , we have used regular expression
/^^[^0-9][a-z0-9]+([_-]?[a-z0-9])*$/ inside the preg_match() function of PHP to match the requirements .

We will use regular expression in the registration form .

Username or email already exists in the Registration form  –

The duplicate data is a bad habit for registration. Every time many unknown users registered with the same username or email. This is a really bad impression if you are going to create a registration form in PHP with the MYSQL database .

We will validate username and email if already exists in PHP .


$sql="select * from users where (username='$username' or email='$email');";
      $res=mysqli_query($dbc,$sql);
   if (mysqli_num_rows($res) > 0) {
$row = mysqli_fetch_assoc($res);

     if($username==$row['username'])
     {
           $error[] ='Username alredy Exists.';
          } 
       if($email==$row['email'])
       {
            $error[] ='Email alredy Exists.';
          } 
      }

In the code above we are fetching the data from the database and check if the username or email already exists in the database. If the username or email exists in the MySQL database then the data doest insert into the MYSQL database. It’s really important for registration form in PHP.

Convert simple text password into the hash pattern in the Registration form–

The hash pattern is a difficult pattern to hack and remember by the user or other unknown hacker. The simple text password can be hacked by the hacker but we will convert the simple text password into the hash pattern. It will be more secured and cannot be hacked by the hacker.

We will use the password_hash() function of PHP in the registration form.


 $options = array("cost"=>4);
    $password = password_hash($password,PASSWORD_BCRYPT,$options);

Insert data into the database using the Registration form in PHP  –

After all validations and checking, the data should be inserted into the MYSQL database table.

In the registration form, we use the insert query to save data into the MYSQL database.


$result = mysqli_query($dbc,"INSERT into users values('','$fname','$lname','$username','$email','$password','$date')");

You will be understood the registration form process through the process details above.

Now, let’s create a file with the name -   signup.php

signup.php


<!DOCTYPE html>
<?php require_once("config.php"); ?>
<html>
<head>
<title> SignUp - Techno Smarter</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"> 
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php if(isset($_POST['signup'])){ extract($_POST); if(strlen($fname)<3){ // Minimum $error[] = 'Please enter First Name using 3 charaters atleast.'; } if(strlen($fname)>20){ // Max $error[] = 'First Name: Max length 20 Characters Not allowed'; } if(!preg_match("/^[A-Za-z _]*[A-Za-z ]+[A-Za-z _]*$/", $fname)){ $error[] = 'Invalid Entry First Name. Please Enter letters without any Digit or special symbols like ( 1,2,3#,$,%,&,*,!,~,`,^,-,)'; } if(strlen($lname)<3){ // Minimum $error[] = 'Please enter Last Name using 3 charaters atleast.'; } if(strlen($lname)>20){ // Max $error[] = 'Last Name: Max length 20 Characters Not allowed'; } if(!preg_match("/^[A-Za-z _]*[A-Za-z ]+[A-Za-z _]*$/", $lname)){ $error[] = 'Invalid Entry Last Name. Please Enter letters without any Digit or special symbols like ( 1,2,3#,$,%,&,*,!,~,`,^,-,)'; } if(strlen($username)<3){ // Change Minimum Lenghth $error[] = 'Please enter Username using 3 charaters atleast.'; } if(strlen($username)>50){ // Change Max Length $error[] = 'Username : Max length 50 Characters Not allowed'; } if(!preg_match("/^^[^0-9][a-z0-9]+([_-]?[a-z0-9])*$/", $username)){ $error[] = 'Invalid Entry for Username. Enter lowercase letters without any space and No number at the start- Eg - myusername, okuniqueuser or myusername123'; } if(strlen($email)>50){ // Max $error[] = 'Email: Max length 50 Characters Not allowed'; } if($passwordConfirm ==''){ $error[] = 'Please confirm the password.'; } if($password != $passwordConfirm){ $error[] = 'Passwords do not match.'; } if(strlen($password)<5){ // min $error[] = 'The password is 6 characters long.'; } if(strlen($password)>20){ // Max $error[] = 'Password: Max length 20 Characters Not allowed'; } $sql="select * from users where (username='$username' or email='$email');"; $res=mysqli_query($dbc,$sql); if (mysqli_num_rows($res) > 0) { $row = mysqli_fetch_assoc($res); if($username==$row['username']) { $error[] ='Username alredy Exists.'; } if($email==$row['email']) { $error[] ='Email alredy Exists.'; } } if(!isset($error)){ $date=date('Y-m-d'); $options = array("cost"=>4); $password = password_hash($password,PASSWORD_BCRYPT,$options); $result = mysqli_query($dbc,"INSERT into users values('','$fname','$lname','$username','$email','$password','$date')"); if($result) { $done=2; } else{ $error[] ='Failed : Something went wrong'; } } } ?>
<?php if(isset($error)){ foreach($error as $error){ echo '

&#x26A0;'.$error.'

'; } } ?>
<?php if(isset($done)) { ?>
&#9989;
You have registered successfully .
Login here...
<?php } else { ?>
</body> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script> </html>

We have already discussed above all about the signup form (The registration form ) in PHP.

Let’s create an advanced CSS file for registration and login form.

Create a file with the name -  style.css

style.css


body{ 
background:#EAE9E5;
 } 
 .login_form{
 	margin-top: 25%;
  background: #fff;
  padding: 30px; 
     box-shadow: 0px 1px 36px 5px rgba(0,0,0,0.28);
     border-radius: 5px;
 }
 .form_btn{ 
 	background: #fb641b;
    box-shadow: 0 1px 2px 0 rgba(0,0,0,.2);
    border: none;
    color: #fff; 
    width: 100% 
  }
  .label_txt{ 
font-size: 12px; 
   }  
   .form-control{border-radius: 25px }
   .signup_form{ 
    background: #fff;
  padding-left: 25px; 
   padding-right: 25px; 
      padding-bottom:5px; 
     box-shadow: 0px 1px 36px 5px rgba(0,0,0,0.28);
     border-radius: 5px;
    }
    .logo{ 
      height: 50px; 
      width: auto; 
        display: block;
  margin-left: auto;
  margin-right: auto;
     }
     .errmsg{ 
  margin: 2px auto;
  border-radius: 5px;
  border: 1px solid red;
  background: pink;
  text-align: left;
  color: brown;
  padding: 1px;
}
.successmsg{
  margin: 5px auto;
  border-radius: 5px;
  border: 1px solid green;
  background: #33CC00;
  text-align: left;
  color: white;
  padding: 10px;
}

This stylesheet will be used to design the registration and login form.

Registration form in PHP | Signup form in PHP with MYSQL

Login form in PHP with MYSQL–

The login form is used to access the restricted pages on the website. Login form helps to secure data from the hackers and crackers on the website.

The login form is another way that users use for their own work and get service by the login.

Let's create a login form.

Create a responsive login form using bootstrap  -

As you know, we have used bootstrap for the registration form above. Now, we will use the same bootstrap and will design a login form.

Create a PHP file with the name – login.php

login.php


<!DOCTYPE html>
<?php require_once("config.php"); ?>
<html>
<head>
<title> Login - Techno Smarter</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css">  <link rel="stylesheet" href="style.css"> </head> <body>
</body> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script> </html>

In the code above, we have created a login form using bootstrap CSS classes.

login form in PHP with MYSQL

Now, we will create PHP scripts for the login form.

Create PHP code for login system in PHP –

In the login form, we have used the session. The session helps secure the pages from unknown unregistered users. 

We can access the value of a session on any page of the website.

Let's create a PHP file with the name  login_process.php

login_process.php


<?php 
require_once("config.php"); 
if(isset($_POST['sublogin'])){ 
$login = $_POST['login_var'];
$password = $_POST['password'];
$query = "select * from users where ( username='$login' OR email = '$login')";
$res = mysqli_query($dbc,$query);
$numRows = mysqli_num_rows($res);
if($numRows  == 1){
        $row = mysqli_fetch_assoc($res);
        if(password_verify($password,$row['password'])){
           $_SESSION["login_sess"]="1"; 
             $_SESSION["login_email"]= $row['email'];
  header("location:account.php");
        }
        else{ 
     header("location:login.php?loginerror=".$login);
        }
    }
    else{
  header("location:login.php?loginerror=".$login);
    }
}
?>

In the PHP code above, we are using a username and email to login account. Users can log in with a username or email.

We have used the password_verify() function to verify the entered password to the database password.

We are creating two-session variables for validation, the session is set or not or second form email. We will access the session email variable value on the account page.

This is a really important part of every login system to get user data on the account page after login.

We will access email and will fetch other user details by the session email variable.

Create an account.php file.

account.php


<!DOCTYPE html>
<?php require_once("config.php");
if(!isset($_SESSION["login_sess"])) 
{
    header("location:login.php"); 
}
  $email=$_SESSION["login_email"];
  $findresult = mysqli_query($dbc, "SELECT * FROM users WHERE email= '$email'");
if($res = mysqli_fetch_array($findresult))
{
$username = $res['username']; 
$fname = $res['fname'];   
$lname = $res['lname'];  
$email = $res['email'];  
}
 ?> 
<html>
<head>
    <title> My Account - Techno Smarter</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"> 
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-3">
        </div>
        <div class="col-sm-6">
     <form action="login_process.php" method="POST">
  <div class="login_form">
 <img src="https://technosmarter.com/assets/images/logo.png" alt="Techno Smarter" class="logo img-fluid"> <br> 
     <p><a href="logout.php"><span style="color:red; float: right;">Logout</span> </a></p>
          <p> Welcome! <span style="color:#33CC00"><?php echo $username; ?></span> </p>
          <table class="table">
          <tr>
              <th>First Name </th>
              <td><?php echo $fname; ?></td>
          </tr>
          <tr>
              <th>Last Name </th>
              <td><?php echo $lname; ?></td>
          </tr>
          <tr>
              <th>Username </th>
              <td><?php echo $username; ?></td>
          </tr>
           <tr>
              <th>Email </th>
              <td><?php echo $email; ?></td>
          </tr>
          </table>
        </div>
        <div class="col-sm-3">
        </div>
    </div>
</div> 
</body>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>
</html>

We are accessing the session variable value. We can use email to fetch data from the database related to the email id using WHERE clause in MYSQL query.

Login account page in PHP | My account page in PHP with MYSQL

Now, we will create a logout page.

Let’s create a logout.php file to destroy the session.

logout.php


<?php require_once("config.php"); 
session_destroy(); 
header("location:login.php"); 
?>

The logout option is really important to secure data from the unknown user. A registered user can log in and logout.

In this way, you can create registration and login forms in PHP.

In the next tutorial, we will create a forgot password and password reset form in PHP  with the MYSQL database.


Recommended Posts:-

Previous Posts:-

Shop Items:-


Integrate PayPal payment gateway in PHP with MYSQL database | PHP scripts

$12



Student result management system for school and college in PHP website

$51



Integrate Payumoney payment gateway in PHP website | Source Scripts

$12