Registration Form In PHP and MySQL With Validation Code

By : PHPErrorCode June 16, 2017 5554 Views php,html,css

Today, mostly in all sites, User account is required to access important features of site. And for that, we are going to create unique email Regestration Form, which is gateway to create user account. We will User Regestration source code using PHP and MySQL database.

We will use prepared statement and Hash function in Regestration form which will prevent SQL Injection and provide better security. You can also create Regestration Form by just following these simple steps and you will find that your first dynamic functional registration form with database entry on every form fill up.

Requirements for Sign-In webpage :
  1. HTML
  2. CSS
  3. JS
  4. Jquery
  5. PHP
  6. MySQL
  7. Xampp / Wamp server
Step 1:  First Create a Database :
  1. Open phpmyadmin
  2. Create database   as "tutorial"
  3. Click create table and name it as "user"
CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `user_name` varchar(25) NOT NULL,
  `email` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Step 2: Front end code, Make HTML Structure of your registration form for registration.php

Create a new file registration.php This is a basic HTML structure file.

<'!DOCTYPE html>
<html>
<head>
  <title>Login</title>
  <link rel="stylesheet" href="custom.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type="text/javascript" src="custom.js"></script>
</head>
<body>
  <form action="add_registration.php" method="post">
    <h2><span class="entypo-login"></span> Registration</h2>
    <button class="submit"><span class="entypo-lock"></span></button>
    <span class="entypo-user inputUserIcon"></span>
    <input type="text" name="user_name" class="user" placeholder="your ursername" required="" />
    <span class="entypo-user inputUserIcon"></span>
    <input type="email" name="email" class="user" placeholder="your email" required="" />
    <span class="entypo-mail inputEmailIcon"></span>
    <input type="password" name="password" class="pass" placeholder="your password" required="" />
    <span class="entypo-key inputPassIcon"></span>
    <input type="password" name="confirm_password" class="pass2" placeholder="confirm your password" required="" />
    <span class="entypo-key inputPassIcon2"></span>
    <?php session_start(); if(isset($_SESSION['err'])){ ?>
    <h2>error.....<?php echo $_SESSION['err']; ?></h2>
    <?php session_unset(); } ?>
  </form>
</body>
</html>
Step 3: Adding javascript to form for custom.js

Create custom.js file with bellow code. This javascript file will check Validation Form data and give clickeffect when user click in Input field.

$(".user").focusin(function(){
  $(".inputUserIcon").css("color", "#e74c3c");
}).focusout(function(){
  $(".inputUserIcon").css("color", "white");
});

$(".pass").focusin(function(){
  $(".inputPassIcon").css("color", "#e74c3c");
}).focusout(function(){
  $(".inputPassIcon").css("color", "white");
});
$(document).ready(function(){
    $(".submit").click(function(){
       var pass1 = $('.pass').val();
       var pass2 = $('.pass2').val();
       if(pass1 != pass2){
          alert("password not match");
          return false;
       }
    });
});
Step 4: Adding styles to form for custom.css

Create custom.css file with bellow code and put its path in regestration.php file. This is standard CSS file which gives styles to Form which makes form looks beautiful.

@import url(http://weloveiconfonts.com/api/?family=entypo);
@import url(http://fonts.googleapis.com/css?family=Roboto);
/* zocial */
[class*="entypo-"]:before {
  font-family: 'entypo', sans-serif;
}

*,
*:before,
*:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box; 
}
h2 {
  color:rgba(255,255,255,.8);
  margin-left:12px;
}
body {
  background: #272125;
  font-family: 'Roboto', sans-serif;
}
form {
  position:relative;
  margin: 50px auto;
  width: 380px;
  height: auto;
}
input {
  padding: 16px;
  border-radius:7px;
  border:0px;
  background: rgba(255,255,255,.2);
  display: block;
  margin: 15px;
  width: 300px;  
  color:white;
  font-size:18px;
  height: 54px;
}
input:focus {
  outline-color: rgba(0,0,0,0);
  background: rgba(255,255,255,.95);
  color: #e74c3c;
}
button {
  float:right;
  height: 260px;
  width: 50px;
  border: 0px;
  background: #e74c3c;
  border-radius:7px;
  padding: 10px;
  color:white;
  font-size:22px;
}
.inputUserIcon {
  position:absolute;
  top:68px;
  right: 80px;
  color:white;
}
.inputEmailIcon {
  position:absolute;
  top:135px;
  right: 80px;
  color:white;
}
.inputPassIcon {
  position:absolute;
  top:200px;
  right: 80px;
  color:white;
}
.inputPassIcon2 {
  position:absolute;
  top: 270px;
  right: 80px;
  color:white;
}
input::-webkit-input-placeholder {
  color: white;
}
input:focus::-webkit-input-placeholder {
  color: #e74c3c;
}
.remember_span{
  color: #cecece;
  font-size: 20px;
}
.remember{
  width: 12%;
  float: left;
  padding: 0px;
  height: 0px;
  margin: 8px;
}
Step 5:For Database connectivity using MySQL:for config.php

This file will gives connection with SQL database with Regestration form.

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tutorial";

  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);

  // Check connection
  if ($conn->connect_error) 
  {
      die("Connection failed: " . $conn->connect_error);
  }
Step 6: Writing logic for user registration script in php for add_registration.php file

Now create add_regestration.php file. All the registration process done in one single php file, in this file we will display an html form for user to register. In the PHP section we will first connect to the database, then we will select the database, if the values are posted, then we are running a MySQL query it will insert the values into the database.

include('config.php');	
session_start();
$error_message="";

//server side validation
if($_POST['user_name'] =="" or $_POST['email']=="" or $_POST['password']=="") 
{
    //Form Required Field Validation 
    $error_message = "All Fields are required";
}
elseif($_POST['password'] != $_POST['confirm_password'])
{
    //Password Matching Validation 
    $error_message = "password not match"; 
}
else
{
    $result = $conn->prepare("SELECT * FROM user where email=?");

    // Bind the variables to the parameter as strings.
    $result->bind_param('s', $_POST['email']);

    // Execute the prepared statement.
    $result->execute();

    // Gets a result set from a prepared statement.
    $result = $result->get_result();

    if($result->num_rows > 0)
    {
        $error_message = "This Email Already exist";
    }
    else
    {
         //Encrypt hash passwords
	 $options = ['cost' => 12];
	 $password = password_hash($_POST['password'], PASSWORD_DEFAULT, $options);

	 if ($data=$conn->prepare("INSERT INTO user (user_name,email,password) VALUES(?,?,?)"))
	 {
	     // Bind the variables to the parameter as strings. 
    	     $data->bind_param("sss", $_POST['user_name'],$_POST['email'],$password);
 
    	     // Execute the prepared statement.
    	     $data->execute();
 
    	     // Close the prepared statement.
    	     $data->close();

	     $_SESSION['user']= $_POST['email'];
	     header("location: Dashboard.php");
         }
         else
         {
              $error_message="Data Filed invalid";
         }
    }
}
if($error_message !="")
{
    $_SESSION['err']=$error_message;
    header("location: registration.php");
}
Step 7:  Add this code in top of header.php

header.php will verify the session, if there is no session it will redirect to registration page.  

include('config.php');
session_start();
if(!isset($_SESSION['user'])){  
    header("Location:registration.php");
}
else
{
    $email= $_SESSION['user'];
    
    if($result = $conn->prepare("select * from user where email=?"))
    {
        // Bind the variables to the parameter as strings. 
    	$result->bind_param('s', $text);
 
        // Execute the prepared statement.
	$result->execute();

        // Gets a result set from a prepared statement.
	$result = $result->get_result();

        // Fetch the table data.
    	$row = $result->fetch_assoc();
    }
    else
    {
        header("Location:registration.php");
    }
}
Step 8: Dashboard.php

<?php include('header.php'); ?>
<!DOCTYPE html>
<html>
<head>
  <title>Desboard</title>
</head>
<body>
  <h1>Wellcome <?php echo $_SESSION['user']; ?></h1>
  <h1><a href="Logout.php">Logout</h1>
</body>
</html>
Step 9: Logout.php

This file will clear all session.

session_start();
session_destroy();
session_unset();
header("location: registration.php");