Luckmoshy
By Luckmoshy · Published:
Last updated: · No comments
  • ARTICLE: PHP LESSON

  • Login and Registration System in PHP (OOP) with MySQL

    This tutorial will take you step-by-step through the entire process of developing a user registration system. A username, password, and email must be provided by users when creating an account. The user can log in to their own account after creating one. After the user logs in, the page will reroute to the dashboard. The user can also log out of his panel. Using PHP, MySQL, and the Oops concept, the entire system was created.

    In this article, we'll show you how to build a dashboard page that can only be accessed by logged-in users. Using this technique, you can build another secure page that users can access only after logging in.

    How to build a PHP and MySQL login and registration system using the oops concept

    Let's look at it. Here are some fundamentally easy steps to building a login registration system.

    1. Create a table in a database.
    2. make a configuration file that will help you call the file using its base URL
    3. for the development of a database connectivity function
    4. Session Creation for Logged In Users
    5. Make an online registration and login form.
    6. Create a Dashboard Page so that a secure access session is built into it once you log in.
    7. Make a (Destroying session) Logout page. 
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    
     <!-- font awesome  -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js">

    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;

    Creating a registration page is necessary after creating a database and table database.

    <?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: bootstrapfriendly@gmail.com</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;
     }
    }

    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>
    function.php
    <?php
    date_default_timezone_set("Africa/Nairobi");
    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 (Destroy session)

    We must end user sessions when we click the logout button. It will go to the login page as a redirect. As a result, make a file called logout.php and add the code below.

    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 must design a safe dashboard page to which we can navigate after logging in.

    <?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

    This article now includes a further page for validating user names and email addresses in order to prevent the use of the same user name and email address when implementing the forgotten password feature using User gmail 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();
    }
    ?>

    You're finished.

    Comments



    What to Learn

    In business and tips are here

    UFllRXRaZDJpLytvYUpFSzZoL1c3NWRTbkltV2VJeEgwMUo1Y3ZvNEU0bz01