Signup and Login using PHP

Pre-requisites: Basic Understanding HTML, CSS, PHP, MySQL, JavaScript and jQuery.

 

In this project,

  • We will create a login and signup page with the help of HTML and CSS.
  • Form validation will be performed using jQuery.
  • Form submission to the server with the help of AJAX.
  • On server end, processing the values with help of MySQLi.
  • Displaying the result status on screen.
  • Create mysite folder in your root directory and create index.php file in it.

 

Run mysite/index.php file in your browser to get the following output. URL may look like as follows:

http://localhost/mysite

 

 

Signup Process

 

Code Explanation of index.php

<link rel="stylesheet" type="text/css" href="css/style.css">

 

  • Style.css file is attached to provide some styles to our page.

 

<script src="js/jquery.js"></script>

 

  • It is necessary to include jQuery file inorder to use jquery functions. You can download it form https://jquery.com.

 

<script src="js/main.js"></script>

 

  •  Form validations and ajax submission script is mentioned in this code.

 

 

<form action="" method="POST" id="signup_form">

  <input type="text" placeholder="Name" name="name" id="name"><br>

  <input type="text" placeholder="Email" name="email" id="email"><br>

  <input type="password" placeholder="Password" name="password" id="pass"><br>

  <input type="password" placeholder="Re-enter Password" name="rpassword" id="rpass">  

  <br>

 <input type="radio" name="gender" value="male" checked="checked"><label>Male</label>

  <input type="radio" name="gender" value="female"><label>Female</label><br>

  <select name="country" id="country">

     <option value="">Select Country</option>

     <option value="India">India</option>

     <option value="Australia">Australia</option>

     <option value="USA">USA</option>

  </select>                            

  <button type="button" name="signup__button" id="signup__button">REGISTER</button>

</form>

 

DESCRIPTION

 

  1. A registration form with “id=signup_form”  has been created with seven fields and one submit button.
  2. Each field is given an id and name attribute with required value. for example :

      <input type="text" placeholder="Name" name="name" id="name">

Where,

  • name input field is given name=”name” and id=”name”.
  • Name attributes are posted to the server while form submission and  Id attribute is used to perform JS validation
  1. Button is also given an id signup__button on which click event is defined. On clicking REGISTER button, we will check for validations and then submit the form through AJAX.

 

 

SIGNUP PROCESS

 

Code Explanation of main.js

 

$("#signup__button").click(function(){

        $("#signup__error").html("");

        var name$("#name");

        var email = $("#email");

        var pass = $("#pass");

        var rpass = $("#rpass");

        var gender = $('input[name="gender"]:checked').val();

        var country = $("#country");

        if(name.val() == ""){

            name.focus();

            $("#signup__error").html("Please Enter Name");

        }else if(email.val() == "" || validateEmail(email.val()) == 0){

            email.focus();

            $("#signup__error").html("Please Enter Email ID");       

        }else if(pass.val() == ""){

            pass.focus();

            $("#signup__error").html("Please enter password");       

        }else if(rpass.val() == ""){

            rpass.focus();

            $("#signup__error").html("Reenter your password");

        }else if(rpass.val() !== pass.val()){

            rpass.focus();

            $("#signup__error").html("Passwords do not match");

            rpass.val("");

        }else if(country.val() == ""){

            country.focus();

            $("#signup__error").html("Please select your country");

        }else{

            $("#signup__error").html("");

            $.ajax({

                type: "POST",

                url: "registration_process.php",

                data: $("#signup_form").serialize(),

                beforeSend: function(){

                    $("#signup__button").html("Please Wait....");

                    $("#signup__button").prop('disabled'true);

                },

                success: function(data){

                    $("#signup__button").html("REGISTER");

                    $("#signup__button").prop('disabled'false);

                    $(this).val("LOGIN");

                    if(data == "success"){

                        $("#signup__error").html("");

                        window.location.href = "welcome.php";

                    }else{

                        $("#signup__error").html("Registration Failed! Try again later."); 

                    }

                }

            });

        }

    });

 

DESCRIPTION

 

  1. Validation for empty field value is performed here. Like :

                  if(name.val() == ""){

            name.focus();

            $("#signup__error").html("Please Enter Name");

   }  

 If name field is empty, it will generate error and display the message in signup__error block. In a similar way, validations are performed for other fields as well. Conditions are added according to the requirement.

  

  1. $.ajax({ });

  Ajax is used for form submission which means form will be submitted to the server without reloading the whole page content.

 

  1. type: "POST",        // HTTP POST METHOD IS USED FOR SUBMISSION

      url: "registration_process.php",    // URL DEFINES WHERE TO POST THE VALUES

      data: $("#signup_form").serialize(),   // DATA CARRIES THE VALUES TO BE POSTED

         These parameters are necessary to mention while form submission.

 

  1. beforeSend: function(){

                     $("#signup__button").html("Please Wait....");

                     $("#signup__button").prop('disabled'true);

                   },

       Here, we have disabled the submit button once it is clicked. It is to avoid unnecessary clicking of submit   

              button again and again, once it is submitted to the server for processing.

 

  1. success: function(data){

                    $("#signup__button").html("REGISTER");

                    $("#signup__button").prop('disabled'false);

                    $(this).val("LOGIN");

                    if(data == "success"){

                        $("#signup__error").html("");

                        window.location.href = "welcome.php";

                    }else{

                        $("#signup__error").html("Registration Failed! Try again later."); 

                    }

                }

        Here, we have enabled the submit button again after receiving response from the server. If registration is

               successful user is moved to welcome.php otherwise error message is displayed on screen.

 


 

SIGNUP PROCESS

 

Code Explanation of registration_process.php

 

$sql = "SELECT id FROM users WHERE username = '".$email."' AND status = '1'";

$res = mysqli_query($con$sql);

$count = mysqli_num_rows($res);

if($count > 0){

   $msg = "Email ID already registered.";

}else{

   $sql = "INSERT INTO `users` 

(`id`, `username`, `password`, `name`, `gender`, `country`, `created_at`, `status`) 

           VALUES 

(NULL, '".$email."', '".$password."', '".$name."', '".$gender."', '".$country."', '".date('Y-m-d H:i:s')."', '1')";

   $res = mysqli_query($con$sql);

   $id = mysqli_insert_id($con);

   if($id > 0){

       @session_start();

       $_SESSION['user'] = $email;

       $_SESSION['name'] = $name;

       $_SESSION['status'] = 1;

       $msg = "success";

    }else{

       $msg = "Some error occured. Please try later.";

    }             

}

 

DESCRIPTION

 

  1. "SELECT id FROM users WHERE username = '".$email."' AND status = '1'";

Users table is checked, if the same email ID exists, it will return an error message otherwise, it will go for further processing.

 

  1. "INSERT INTO `users` 

(`id`, `username`, `password`, `name`, `gender`, `country`, `created_at`, `status`) 

           VALUES 

(NULL, '".$email."', '".$password."', '".$name."', '".$gender."', '".$country."', '".date('Y-m-d H:i:s')."', '1')";

Values are inserted in users tables according to the syntax:

  INSERT INTO tablename (columns…) VALUES (values….)

 

  1. On successful insertion, session is started and message success is generated.

 


 

SIGNUP PROCESS

 

Code Explanation of welcome.php

 

<?php

    session_start();

    if(!isset($_SESSION['user']) || $_SESSION['user'] == ''){

        header("Location:index.php");

    }

?>

<!DOCTYPE html>

<html>

    <head>

        <title>WELCOME <?=ucfirst($_SESSION['name'])?></title>

        <link rel="stylesheet" type="text/css" href="css/style.css">

    </head>

    <body>

        <div class="wrap">

            <header>

                <div class="left">

                    <h2>Hello <?=ucfirst($_SESSION['name'])?></h2>

                </div>

                <div class="right">

                    <a href="logout.php">Logout</a>

                </div>

            </header>

        </div>

    </body>

</html>

 

 

DESCRIPTION

 

  1. session_start();

      if(!isset($_SESSION['user']) || $_SESSION['user'] == ''){

         header("Location:index.php");

      }

Welcome.php will be loaded only if session will exist. Otherwise, user will be moved to index.php.

 


 

SIGNUP PROCESS

 

Code Explanation of logout.php

<?php

    session_start();

    session_destroy();

    header("Location:index.php");

?>

 

 

DESCRIPTION

 

  1. Sessions are destroyed and the user is moved to main page.

 

 

SIGNIN PROCESS

 

Code Explanation of index.php

<link rel="stylesheet" type="text/css" href="css/style.css">

 

  • Style.css file is attached to provide some styles to our page.

 

<script src="js/jquery.js"></script>

 

  • It is necessary to include jQuery file inorder to use jquery functions. You can download it form https://jquery.com.

 

<script src="js/main.js"></script>

 

  •  Form validations and ajax submission script is mentioned in this code.

 

<form action="" method="POST" id="login_form">

      <input type="text" placeholder="Email" id="login_email" name="username"><br>

      <input type="password" placeholder="Password" id="login_pass" name="password"><br>

      <button type="button" id="login_button">LOGIN</button>

</form>

 

DESCRIPTION

 

  1. A signin form with “id=login_form” has been created with two fields and one submit button.
  2. Each field is given an id and name attribute with required value. for example :

                  <input type="text" placeholder="Email" name="username" id="login_email">

      Where,

  • Email input field is given name=”username” and id=”login_email”.
  • Name attributes are posted to the server while form submission and  Id attribute is used to perform JS validation
  1. Button is also given an id login_button on which click event is defined. On clicking LOGIN button, we will check for validations and then submit the form through AJAX.

 

 

 

SIGNIN PROCESS

 

Code Explanation of main.js

$("#login_button").click(function(){

        var email = $("#login_email");

        var pass = $("#login_pass");

        if(email.val() == "" || validateEmail(email.val()) == 0){

            email.focus();

            $("#login__error").html("Please enter valid email");       

        }else if(pass.val() == ""){

            pass.focus();

            $("#login__error").html("Please enter password");       

        }else{

            $("#login__error").html("");

            $.ajax({

                type: "POST",

                url: "process.php",

                data: $("#login_form").serialize(),

                beforeSend: function(){

                    $("#login_button").html("Please Wait....");

                    $("#login_button").prop('disabled'true);

                },

                success: function(data){

                    $("#login_button").html("LOGIN");

                    $("#login_button").prop('disabled'false);

                    $(this).val("LOGIN");

                    if(data == 1){

                        window.location.href = "welcome.php";

                    }else{

                        $("#login__error").html("Please enter valid login details"); 

                    }

                }

            });

        }

});

 

 

DESCRIPTION

 

 

  1. Validation for empty field value is performed here. Like :

                   if(email.val() == "" || validateEmail(email.val()) == 0){

            email.focus();

            $("#login__error").html("Please enter valid email");       

    }  

 If email field is empty, it will generate error and display the message in login__error block. In a similar way, validations are performed for other fields as well. Conditions are added according to the requirement.

  

  1. $.ajax({ });

  Ajax is used for form submission which means form will be submitted to the server without reloading the whole page content.

 

  1. type: "POST",        // HTTP POST METHOD IS USED FOR SUBMISSION

         url: "process.php",    // URL DEFINES WHERE TO POST THE VALUES

         data: $("#login_form").serialize(),   // DATA CARRIES THE VALUES TO BE POSTED

         These parameters are necessary to mention while form submission.

 

  1. beforeSend: function(){

                       $("#login_button").html("Please Wait....");

                       $("#login_button").prop('disabled'true);

                   },

       Here, we have disabled the submit button once it is clicked. It is to avoid unnecessary clicking of submit   

              button again and again, once it is submitted to the server for processing.

 

  1. success: function(data){

                      $("#login_button").html("LOGIN");

                      $("#login_button").prop('disabled'false);

                      $(this).val("LOGIN");

                      if(data == 1){

                          window.location.href = "welcome.php";

                      }else{

                          $("#login__error").html("Please enter valid login details"); 

                      }

                  }

        Here, we have enabled the submit button again after receiving response from the server. If login is

               successful user is moved to welcome.php otherwise error message is displayed on screen.

 

 

Summary

In this project, we have learned to create login/ signup page.

HTML and CSS are used to create the layout of webpages.

Form validations are performed using jQuery in main.js file which is included in the head tag for index file.

Ajax is used to submit the forms without reloading the whole webpage.

MySQLi queries are used to connect to a database and save/retrieve data as per the requirement.

PREREQUISITES: Basic Understanding HTML, CSS, PHP, MySQL, JavaScript and jQuery.

In this project,

  • We will create a login and signup page with the help of HTML and CSS.
  • Form validation will be performed using jQuery.
  • Form submission to the server with the help of AJAX.
  • On server end, processing the values with help of MySQLi.
  • Displaying the result status on screen.

Create mysite folder in your root directory and create index.php file in it.

 

 

 

Run mysite/index.php file in your browser to get the following output. URL may look like as follows:

                                    http://localhost/mysite

 

 

SIGNUP PROCESS

Code Explanation of index.php

 

<link rel="stylesheet" type="text/css" href="css/style.css">

 

  • Style.css file is attached to provide some styles to our page.

 

<script src="js/jquery.js"></script>

 

  • It is necessary to include jQuery file inorder to use jquery functions. You can download it form https://jquery.com.

 

<script src="js/main.js"></script>

 

  •  Form validations and ajax submission script is mentioned in this code.

 

 

<form action="" method="POST" id="signup_form">

  <input type="text" placeholder="Name" name="name" id="name"><br>

  <input type="text" placeholder="Email" name="email" id="email"><br>

  <input type="password" placeholder="Password" name="password" id="pass"><br>

  <input type="password" placeholder="Re-enter Password" name="rpassword" id="rpass">  

  <br>

 <input type="radio" name="gender" value="male" checked="checked"><label>Male</label>

  <input type="radio" name="gender" value="female"><label>Female</label><br>

  <select name="country" id="country">

     <option value="">Select Country</option>

     <option value="India">India</option>

     <option value="Australia">Australia</option>

     <option value="USA">USA</option>

  </select>                            

  <button type="button" name="signup__button" id="signup__button">REGISTER</button>

</form>

 

DESCRIPTION

 

  1. A registration form with “id=signup_form”  has been created with seven fields and one submit button.
  2. Each field is given an id and name attribute with required value. for example :

      <input type="text" placeholder="Name" name="name" id="name">

Where,

  • name input field is given name=”name” and id=”name”.
  • Name attributes are posted to the server while form submission and  Id attribute is used to perform JS validation
  1. Button is also given an id signup__button on which click event is defined. On clicking REGISTER button, we will check for validations and then submit the form through AJAX.

 


 

SIGNUP PROCESS

Code Explanation of main.js

 

 

$("#signup__button").click(function(){

        $("#signup__error").html("");

        var name$("#name");

        var email = $("#email");

        var pass = $("#pass");

        var rpass = $("#rpass");

        var gender = $('input[name="gender"]:checked').val();

        var country = $("#country");

        if(name.val() == ""){

            name.focus();

            $("#signup__error").html("Please Enter Name");

        }else if(email.val() == "" || validateEmail(email.val()) == 0){

            email.focus();

            $("#signup__error").html("Please Enter Email ID");       

        }else if(pass.val() == ""){

            pass.focus();

            $("#signup__error").html("Please enter password");       

        }else if(rpass.val() == ""){

            rpass.focus();

            $("#signup__error").html("Reenter your password");

        }else if(rpass.val() !== pass.val()){

            rpass.focus();

            $("#signup__error").html("Passwords do not match");

            rpass.val("");

        }else if(country.val() == ""){

            country.focus();

            $("#signup__error").html("Please select your country");

        }else{

            $("#signup__error").html("");

            $.ajax({

                type: "POST",

                url: "registration_process.php",

                data: $("#signup_form").serialize(),

                beforeSend: function(){

                    $("#signup__button").html("Please Wait....");

                    $("#signup__button").prop('disabled'true);

                },

                success: function(data){

                    $("#signup__button").html("REGISTER");

                    $("#signup__button").prop('disabled'false);

                    $(this).val("LOGIN");

                    if(data == "success"){

                        $("#signup__error").html("");

                        window.location.href = "welcome.php";

                    }else{

                        $("#signup__error").html("Registration Failed! Try again later."); 

                    }

                }

            });

        }

    });

 

DESCRIPTION

 

  1. Validation for empty field value is performed here. Like :

                  if(name.val() == ""){

            name.focus();

            $("#signup__error").html("Please Enter Name");

   }  

 If name field is empty, it will generate error and display the message in signup__error block. In a similar way, validations are performed for other fields as well. Conditions are added according to the requirement.

  

  1. $.ajax({ });

  Ajax is used for form submission which means form will be submitted to the server without reloading the whole page content.

 

  1. type: "POST",        // HTTP POST METHOD IS USED FOR SUBMISSION

      url: "registration_process.php",    // URL DEFINES WHERE TO POST THE VALUES

      data: $("#signup_form").serialize(),   // DATA CARRIES THE VALUES TO BE POSTED

         These parameters are necessary to mention while form submission.

 

  1. beforeSend: function(){

                     $("#signup__button").html("Please Wait....");

                     $("#signup__button").prop('disabled'true);

                   },

       Here, we have disabled the submit button once it is clicked. It is to avoid unnecessary clicking of submit   

              button again and again, once it is submitted to the server for processing.

 

  1. success: function(data){

                    $("#signup__button").html("REGISTER");

                    $("#signup__button").prop('disabled'false);

                    $(this).val("LOGIN");

                    if(data == "success"){

                        $("#signup__error").html("");

                        window.location.href = "welcome.php";

                    }else{

                        $("#signup__error").html("Registration Failed! Try again later."); 

                    }

                }

        Here, we have enabled the submit button again after receiving response from the server. If registration is

               successful user is moved to welcome.php otherwise error message is displayed on screen.

 


 

SIGNUP PROCESS

Code Explanation of registration_process.php

 

 

$sql = "SELECT id FROM users WHERE username = '".$email."' AND status = '1'";

$res = mysqli_query($con$sql);

$count = mysqli_num_rows($res);

if($count > 0){

   $msg = "Email ID already registered.";

}else{

   $sql = "INSERT INTO `users` 

(`id`, `username`, `password`, `name`, `gender`, `country`, `created_at`, `status`) 

           VALUES 

(NULL, '".$email."', '".$password."', '".$name."', '".$gender."', '".$country."', '".date('Y-m-d H:i:s')."', '1')";

   $res = mysqli_query($con$sql);

   $id = mysqli_insert_id($con);

   if($id > 0){

       @session_start();

       $_SESSION['user'] = $email;

       $_SESSION['name'] = $name;

       $_SESSION['status'] = 1;

       $msg = "success";

    }else{

       $msg = "Some error occured. Please try later.";

    }             

}

 

DESCRIPTION

 

  1. "SELECT id FROM users WHERE username = '".$email."' AND status = '1'";

Users table is checked, if the same email ID exists, it will return an error message otherwise, it will go for further processing.

 

  1. "INSERT INTO `users` 

(`id`, `username`, `password`, `name`, `gender`, `country`, `created_at`, `status`) 

           VALUES 

(NULL, '".$email."', '".$password."', '".$name."', '".$gender."', '".$country."', '".date('Y-m-d H:i:s')."', '1')";

Values are inserted in users tables according to the syntax:

  INSERT INTO tablename (columns…) VALUES (values….)

 

  1. On successful insertion, session is started and message success is generated.

 


 

 

SIGNUP PROCESS

Code Explanation of welcome.php

 

 

<?php

    session_start();

    if(!isset($_SESSION['user']) || $_SESSION['user'] == ''){

        header("Location:index.php");

    }

?>

<!DOCTYPE html>

<html>

    <head>

        <title>WELCOME <?=ucfirst($_SESSION['name'])?></title>

        <link rel="stylesheet" type="text/css" href="css/style.css">

    </head>

    <body>

        <div class="wrap">

            <header>

                <div class="left">

                    <h2>Hello <?=ucfirst($_SESSION['name'])?></h2>

                </div>

                <div class="right">

                    <a href="logout.php">Logout</a>

                </div>

            </header>

        </div>

    </body>

</html>

 

 

DESCRIPTION

 

  1. session_start();

      if(!isset($_SESSION['user']) || $_SESSION['user'] == ''){

         header("Location:index.php");

      }

Welcome.php will be loaded only if session will exist. Otherwise, user will be moved to index.php.

 


 

SIGNUP PROCESS

Code Explanation of logout.php

 

<?php

    session_start();

    session_destroy();

    header("Location:index.php");

?>

 

 

DESCRIPTION

 

  1. Sessions are destroyed and the user is moved to main page.

 

 

 

SIGNIN PROCESS

Code Explanation of index.php

 

<link rel="stylesheet" type="text/css" href="css/style.css">

 

  • Style.css file is attached to provide some styles to our page.

 

<script src="js/jquery.js"></script>

 

  • It is necessary to include jQuery file inorder to use jquery functions. You can download it form https://jquery.com.

 

<script src="js/main.js"></script>

 

  •  Form validations and ajax submission script is mentioned in this code.

 

<form action="" method="POST" id="login_form">

      <input type="text" placeholder="Email" id="login_email" name="username"><br>

      <input type="password" placeholder="Password" id="login_pass" name="password"><br>

      <button type="button" id="login_button">LOGIN</button>

</form>

 

DESCRIPTION

 

  1. A signin form with “id=login_form” has been created with two fields and one submit button.
  2. Each field is given an id and name attribute with required value. for example :

                  <input type="text" placeholder="Email" name="username" id="login_email">

      Where,

  • Email input field is given name=”username” and id=”login_email”.
  • Name attributes are posted to the server while form submission and  Id attribute is used to perform JS validation
  1. Button is also given an id login_button on which click event is defined. On clicking LOGIN button, we will check for validations and then submit the form through AJAX.

 

 

 

SIGNIN PROCESS

Code Explanation of main.js

 

$("#login_button").click(function(){

        var email = $("#login_email");

        var pass = $("#login_pass");

        if(email.val() == "" || validateEmail(email.val()) == 0){

            email.focus();

            $("#login__error").html("Please enter valid email");       

        }else if(pass.val() == ""){

            pass.focus();

            $("#login__error").html("Please enter password");       

        }else{

            $("#login__error").html("");

            $.ajax({

                type: "POST",

                url: "process.php",

                data: $("#login_form").serialize(),

                beforeSend: function(){

                    $("#login_button").html("Please Wait....");

                    $("#login_button").prop('disabled'true);

                },

                success: function(data){

                    $("#login_button").html("LOGIN");

                    $("#login_button").prop('disabled'false);

                    $(this).val("LOGIN");

                    if(data == 1){

                        window.location.href = "welcome.php";

                    }else{

                        $("#login__error").html("Please enter valid login details"); 

                    }

                }

            });

        }

});

 

 

DESCRIPTION

 

 

  1. Validation for empty field value is performed here. Like :

                   if(email.val() == "" || validateEmail(email.val()) == 0){

            email.focus();

            $("#login__error").html("Please enter valid email");       

    }  

 If email field is empty, it will generate error and display the message in login__error block. In a similar way, validations are performed for other fields as well. Conditions are added according to the requirement.

  

  1. $.ajax({ });

  Ajax is used for form submission which means form will be submitted to the server without reloading the whole page content.

 

  1. type: "POST",        // HTTP POST METHOD IS USED FOR SUBMISSION

         url: "process.php",    // URL DEFINES WHERE TO POST THE VALUES

         data: $("#login_form").serialize(),   // DATA CARRIES THE VALUES TO BE POSTED

         These parameters are necessary to mention while form submission.

 

  1. beforeSend: function(){

                       $("#login_button").html("Please Wait....");

                       $("#login_button").prop('disabled'true);

                   },

       Here, we have disabled the submit button once it is clicked. It is to avoid unnecessary clicking of submit   

              button again and again, once it is submitted to the server for processing.

 

  1. success: function(data){

                      $("#login_button").html("LOGIN");

                      $("#login_button").prop('disabled'false);

                      $(this).val("LOGIN");

                      if(data == 1){

                          window.location.href = "welcome.php";

                      }else{

                          $("#login__error").html("Please enter valid login details"); 

                      }

                  }

        Here, we have enabled the submit button again after receiving response from the server. If login is

               successful user is moved to welcome.php otherwise error message is displayed on screen.

 

 

 

Summary

 

In this project, we have learned to create login/ signup page.

  • HTML and CSS are used to create the layout of webpages.
  • Form validations are performed using jQuery in main.js file which is included in the head tag for index file.
  • Ajax is used to submit the forms without reloading the whole webpage.
  • MySQLi queries are used to connect to a database and save/retrieve data as per the requirement.

Help Us to Improve our content

Let's Talk
Go back to Previous Course

© 2021 Lecturely.com. All rights reserved.

Lecturely.com – Imagined by Paras Jairath, Developed by P3 Multisolutions & Powered by Network Bulls.