Login and Registration System in PHP and MySQL with oops concept

Hello, friends in this article we will discuss How to create a Registration and Login System in PHP and MySQL with the oops concept. Here is the quick solution to build a login system in PHP and MySQL with the oops concept.  Every modern website or web application provides Registration and login functionality. So, it is necessary to add a login system in modern web applications.

In this tutorial, we walk through the complete process of creating a user registration system. Users can create an account by providing a username, password, email. After the account was created, the user can log in to their own account. Once the user login, it will redirect to the Dashboard page. Moreover, the user can logout from his panel. This whole system we are developed using PHP and MySQL with the oops concept.

In this article, we build a dashboard page which only accessible for logged-in users, and this tactic will help you to create another secure page that will be accessible only after login.

How to create a  Login and Registration   System in PHP and MySQL with oops concept

Let's have a look. Here are basic simple steps that help you to build a login registration system.

  1. Create a Database and Database Table
  2. create a config file  for helping to call the file with the base url
  3. Creat database connectivity function
  4. Create  Session for Logged in User
  5. Create a Registration and Login Form
  6. Make a Dashboard Page   session will inbuild in this page for secure access after login
  7. Create a Logout page for  (Destroying session) 


Tree directory structure  script With PHP

Let's have a look at the file structure:


Create a Database and Database Table

Similarly, you can execute the below query to create a database.

CREATE DATABASE [IF NOT EXISTS] bootstrapfriendly_db;


and then the second step to creating a user table. The user's table will have the following fields.

  • id int(11)
  • FullName   varchar(100)
  • Username  varchar(100)
  • UserEmail  varchar(100)
  • Password   varchar(100)
  • RegDate  datetime

SQL query:

        
        CREATE TABLE tblusers (
  `id` int(11) NOT NULL,
  `FullName` varchar(120) DEFAULT NULL,
  `Username` varchar(120) DEFAULT NULL,
  `UserEmail` varchar(200) DEFAULT NULL,
  `Password` varchar(250) DEFAULT NULL,
  `RegDate` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
        
    
After creating a database and table database we need to creat a registration page
        
        <?php
require_once("config/config.php");

require_once(ROOT_PATH.'/libs/function.php');
// Object creation
$userdata=new DB_con();
if(isset($_POST['submit']))
{
// Posted Values
$fname=$_POST['fullname'];
$uname=$_POST['username'];
$uemail=$_POST['email'];
$pasword=md5($_POST['password']);
//Function Calling
$sql=$userdata->registration($fname,$uname,$uemail,$pasword);
  if($sql)
  {

  header("Location:index.php");
  }
  else
  {
    // Message for unsuccessfull insertion
    echo "Something went wrong. Please try again";
    header("Location:index.php");
  }
}
?>


<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">


    <title>Login registration with remember me</title>

  <style>

  </style>


  </head>
  <body>

    <div class="container p-4">
      <div class="row d-flex justify-content-center">
        <div class="col-sm-6 border p-4 bg-light">
          <form action="" method="post" id="login" onsubmit="return checkall();">
          <h4> PHP registration with oops concept</h4>

            <div class="form-group">
              <label for="fullname">Full Name</label>
              <input name="fullname" type="text"  class="form-control"
              id="fullname" placeholder="" required="true">
            </div>

            <div class="form-group">
               <label for="username">User Name</label>
               <input type="text" id="username" name="username" onkeyup="check_uname()" class="form-control"  required="true">
               <span id="name_status"></span>
            </div>

            <div class="form-group">
              <label for="email">Email</label>
              <input type="email" id="email" name="email" onkeyup="checkemail()" placeholder="" class="form-control" required="true">
              <span id="email_status"></span>
            </div>


            <div class="form-group">
              <label for="password">Password</label>

               <input type="password"  id="password" name="password" placeholder="" class="form-control"  required="true">



            </div>

            <div class="col-sm-12 text-right">
               <button class="btn btn-primary" type="submit" id="submit" name="submit">Register</button>
            </div>

            <div class="col-sm-12 text-right">
               <p>Already registered <a href="index.php">Login</a></p>
            </div>

            <div class="col-12 pt-4">
              <em>
                <p><b>bellwo user name and email is already available:</b></p>
                <p>user: admin</p>
                <p>user: [email protected]</p>
              </em>
            </div>

          </form>
        </div>
      </div>
    </div>


<script>
function check_uname()
{
 var uname=document.getElementById( "username" ).value;

 if(uname)
 {
    $.ajax({
    type: 'post',
    url: 'libs/checkdata.php',
    data: {
     username:uname,
    },
    success: function (response) {
     $( '#name_status' ).html(response);
     if(response=="Available")
     {
      $(".form-group span").addClass("text-success");
      return true;
     }
     else
     {
      return false;
     }
    }
    });
 }

 else
 {
  $('#name_status').html("");
  return false;
 }
}

function checkemail()
{
 var uemail=document.getElementById( "email" ).value;

 if(email)
 {
  $.ajax({
  type: 'post',
  url: 'libs/checkdata.php',
  data: {
   email:uemail,
  },
  success: function (response) {
   $( '#email_status' ).html(response);
   if(response=="Available")
   {
    $(".form-group span").addClass("text-success");
    return true;
   }
   else
   {
    return false;
   }
  }
  });
 }
 else
 {
  $( '#email_status' ).html("");
  return false;
 }
}

function checkall()
{
 var namehtml=document.getElementById("name_status").innerHTML;
 var emailhtml=document.getElementById("email_status").innerHTML;

 if((namehtml && emailhtml)=="Available")
 {
  $(".form-group span").addClass("text-success");
  return true;
 }
 else
 {
  return false;
 }
}
        
    

Related Post

Now Create login.php 

        
        <?php
session_start();

require_once("config/config.php");

require_once(ROOT_PATH.'/libs/function.php');
$usercredentials=new DB_con();

//fetching username from either session or cookies condition
if(isset($_SESSION["uid"]) || isset($_COOKIE['user_login'])) {
  $uname = $uun = $uup = "";
  if (isset($_SESSION["uname"])) {
    $uname  = $_SESSION['uname'];
  }
  if (isset($_COOKIE['user_login'])) {
    $uname  = $_COOKIE['user_login'];
  }

  $query="SELECT*FROM tblusers  WHERE Username='$uname'";

      $result= $usercredentials->runBaseQuery($query);

      foreach ($result as $k => $v)
      {
        $uun = $result[$k]['Username'];
        $uup = $result[$k]['Password'];
      }
}


// login function start
if(isset($_POST['signin']))
{
// Posted Values
$uname=$_POST['username'];
$pasword=md5($_POST['password']);
//Function Calling
$ret=$usercredentials->signin($uname,$pasword);
$num=mysqli_fetch_array($ret);
if($num>0)
{
  $_SESSION['uid']=$num['id'];
  $_SESSION['uname']=$uname;


      if(!empty($_POST["remember"])) {

        setcookie ("user_login",$_POST["username"],time()+ (10 * 365 * 24 * 60 * 60), "/");

        setcookie ("userpassword",$_POST["password"],time()+ (10 * 365 * 24 * 60 * 60), "/");

      } else {

        if(isset($_COOKIE["user_login"])) {

          setcookie ("user_login","");

        }

        if(isset($_COOKIE["userpassword"])) {
          setcookie ("userpassword","");
          setcookie ("userpassword","");

        }

      }

header("Location:dashboard.php");
}
else
{

header("Location:index.php");
}
}
?>

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">




    <title>Signin Admin</title>
    <style>


  </style>

  </head>
  <body>


    <!-- nnn -->
<div class="container-fluid  ">
  <div class="row d-flex justify-content-center align-items-center" style="height: 100vh;">
    <div class="col-sm-3 p-4 bg-light border">

      <form action="" method="post" id="login" autocomplete="off">
        <div class="form-row">

          <h4 class="title my-3">Login For Access</h4>
          <div class="col-12">
            <div class="input-group mb-3">
              <div class="input-group-prepend">
                <span class="input-group-text" id="basic-addon1"><i class="fas fa-user"></i></span>
              </div>
              <input name="username" type="text" value="<?php if(isset($_COOKIE["user_login"])) { echo $_COOKIE["user_login"]; } ?>" class="input form-control" id="username" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1">
            </div>
          </div>

          <div class="col-12">
            <div class="input-group mb-3 w-100">
              <div class="input-group-prepend">
                <span class="input-group-text" id="basic-addon1"><i class="fas fa-lock"></i></span>
              </div>
              <input name="password" type="password" value="" class="input form-control" id="password" placeholder="password" required="true" aria-label="password" aria-describedby="basic-addon1">
            </div>
          </div>

          <div class="col-6">
            <div class="form-group form-check text-left">
                <input type="checkbox" name="remember" <?php if(isset($_COOKIE["user_login"])) { ?> checked <?php } ?>  class="form-check-input"
                id="remember_me">
                <label class="form-check-label" for="remember_me">Remember me</label>
            </div>

          </div>
          <div class="col-sm-12 pt-3 text-right">
               <p>Already registered <a href="register.php">Register</a></p>
          </div>

          <div class="col-12">
            <button class="btn btn-primary" type="submit"  name="signin">Login</button>
          </div>

            <!-- <div class="col-12 pt-4">
              <em>
                <p><b>use bellwo user name and password for login:</b></p>
                <p>user: admin</p>
                <p>user: 123</p>
              </em>
            </div> -->

        </div>


      </form>

    </div>
  </div>
</div>



  </body>
</html>
        
    

Now Create function.php for handling the request

        
        <?php
date_default_timezone_set("Asia/Kolkata");
define('DB_SERVER','localhost');
define('DB_USER','bfriendly_u');
define('DB_PASS' ,'12345');
define('DB_NAME', 'bootstrapfriendly_demo');
class DB_con
{
function __construct()
{
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
$this->dbh=$con;
// Check connection
if (mysqli_connect_errno())
{
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }
}

// for username availblty
public function usernameavailblty($uname) {
	$result =mysqli_query($this->dbh,"SELECT Username FROM tblusers WHERE Username='$uname'");
	return $result;
}

// for email availblty
public function uemailavailblty($email) {
	$result =mysqli_query($this->dbh,"SELECT UserEmail FROM tblusers WHERE UserEmail='$email'");
	return $result;
}

// Function for registration
public function registration($fname,$uname,$uemail,$pasword)
{
$ret=mysqli_query($this->dbh,"insert into tblusers(FullName,Username,UserEmail,Password) values('$fname','$uname','$uemail','$pasword')");
return $ret;
}


// Function for signin
public function signin($uname,$pasword)
	{
	$result=mysqli_query($this->dbh,"select id,FullName from tblusers where Username='$uname' and Password='$pasword'");
	return $result;
	}

    function runBaseQuery($query) {
                $result = mysqli_query($this->dbh, $query);
                while($row=mysqli_fetch_assoc($result)) {
                $resultset[] = $row;
                }
                if(!empty($resultset)){
                return $resultset;
                }
    }

    function numRows($query) {
        $result  = mysqli_query($this->dbh, $query);
        $rowcount = mysqli_num_rows($result);
        return $rowcount;
    }

    function executeQuery($query) {
        $result  = mysqli_query($this->dbh, $query);
        return $result;
    }

}
?>
        
    

Create a Logout page

When clicking on the logout button we have to destroy user sessions. It will redirect to the login page. Thus, create a file named logout.php and add the below code.

logout.php

        
        <?php
session_start();
$_SESSION["uid"] = "";

if(isset($_COOKIE['user_login']))
{
 setcookie ("user_login","",time()- (90 * 365 * 24 * 60 * 60), "/");
 setcookie("user_login", "");
}
session_destroy();
header("Location:index.php");
?>
        
    

Creating a dashboard page

Finally, we need to create a secure  dashboard page where we can jump after login

        
        <?php
session_start();

require_once("config/config.php");

if(isset($_SESSION["uid"]) || isset($_COOKIE['user_login'])) {
  include_once(ROOT_PATH.'/libs/function.php');
  $usercredentials=new DB_con();

  //fetching username from either session or cookies condition
  $uname = $uun = $uup = "";
  if (isset($_SESSION["uname"])) {
    $uname  = $_SESSION['uname'];
  }
  if (isset($_COOKIE['user_login'])) {
    $uname  = $_COOKIE['user_login'];
  }

  $query="SELECT*FROM tblusers  WHERE Username='$uname'";

      $result= $usercredentials->runBaseQuery($query);

      foreach ($result as $k => $v)
      {
        $uun = $result[$k]['Username'];
        $uup = $result[$k]['Password'];
      }
//session  condition  end  but it follows until bottom of the page


?>


<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">


    <!-- <link href="assests/style.css" rel="stylesheet"> -->
    <title>Signin Admin</title>
    <style>


  </style>

  </head>
  <body>


    <!-- nnn -->
<div class="container-fluid bg-light ">
<div class="container">
  <div class="row" style="min-height: 100vh;">
    <div class="col-sm-12 p-4 bg-white">

      <a href="logout.php" class="btn btn-warning">
        Logout
      </a>

      <h1>Hello, <strong><?php echo $uun;?>!</strong></h1>
      <h2>Welcome to admnin dashboard</h2>

      <p>Lorem ipsum dolor sit amet, consectetur, adipisicing elit. Obcaecati, illo, praesentium cumque sint beatae magni perspiciatis quos odio et sit, molestiae cupiditate eum quae laboriosam ea rem nemo eveniet aut.</p>

      <p>Lorem ipsum dolor sit amet, consectetur, adipisicing elit. Obcaecati, illo, praesentium cumque sint beatae magni perspiciatis quos odio et sit, molestiae cupiditate eum quae laboriosam ea rem nemo eveniet aut.</p>
      <p>Lorem ipsum dolor sit amet, consectetur, adipisicing elit. Obcaecati, illo, praesentium cumque sint beatae magni perspiciatis quos odio et sit, molestiae cupiditate eum quae laboriosam ea rem nemo eveniet aut.</p>


    </div>
  </div>
</div>
</div>



<script type="text/javascript">
        
    

Creating a username and email availability checking page

One more page we added in this article for validating user name and email address so that same user name and email we are not allowing it's a very important thing while implementing forgot password page with the help of User email or user name.

checkdata.php

        
        <?php
// include Function  file
include_once('function.php');
// Object creation
$u_p_obj=new DB_con();

if(isset($_POST['username']))
{
 $uname= $_POST["username"];

	// Calling function for username
	$sql=$u_p_obj->usernameavailblty($uname);
	$num=mysqli_num_rows($sql);

 if($num>0)
 {
  echo "<span class='text-danger'>User Name Already Exist</span>";
 }
 else
 {
  echo "Available";
 }
 exit();
}

if(isset($_POST['email']))
{
 $email= $_POST["email"];
    // Calling function for email
	$sql2=$u_p_obj->uemailavailblty($email);

	$num2=mysqli_num_rows($sql2);

 if($num2>0)
 {
  echo "<span class='text-danger'>Email Already Exist</span>";
 }
 else
 {
  echo "Available";
 }
 exit();
}
?>
        
    

Leave a comment