Simple OOPS based login and registration script in php and mysql

This is premium tutorial for all core php developers whose first task is to create signin and signup feature for any web based applications.

So here i come up with the latest oops based signin and signup script for geek php developers who loves oops concept. this script fully developed in oops concept with exceptional handling support PHP V5.5+

php-auth



So lets start tutorial..

Step:1- Create database php-auth

Step:2- Create users table where user login information will be store.

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Step:3- Your project directory and file structure will be.

+-php-auth
+---css
+---js
+---classes
+-----dbconfig.php
+-----userClass.php
+---function.php
+---header.php
+---footer.php
+---index.php
+---registration.php
+---profile.php

Step:4- Now create our first class file to connect database.

classes/dbconfig.php

<?php
class dbconfig {
  
  protected static $host = "localhost";
  
  protected static $username = "root";
  
  protected static $password = "root";
  
  protected static $dbname = "php-auth";
 
  static $con;
 
  function __construct() {
    self::$con = self::connect(); 
  }
 
  
  protected static function connect() {
     try {
       $link = mysqli_connect(self::$host, self::$username, self::$password, self::$dbname); 
        if(!$link) {
          throw new exception(mysqli_error($link));
        }
        return $link;
     } catch (Exception $e) {
       echo "Error: ".$e->getMessage();
     } 
  }
 
 
  public static function close() {
     mysqli_close(self::$con);
  }
 

  public static function run($query) {
    try {
      if(empty($query) && !isset($query)) {
        throw new exception("Query string is not set.");
      }
      $result = mysqli_query(self::$con, $query);
      //self::close();
     return $result;
    } catch (Exception $e) {
      echo "Error: ".$e->getMessage();
    }
 
  } 
 
}

Update above file with your database credentials.

Step:5- Now create another class file which handle your all user’s business logic and database operation like user registration, login, profile etc.

classes/userClass.php

<?php

require_once("dbconfig.php");
class USER extends dbconfig {
 
   public static $data;
 
   function __construct() {
     parent::__construct();
   }
 
 
   public static function addNewUser($userData) {
     try {
       $check = self::checkUserExist($userData['username']);
       if($check['status'] == 'error') {
       $data = $check;
       } else {
       $query = "INSERT INTO users (name, username, password) ";
       $query .= "VALUES ('".$userData['name']."', '".$userData['username']."', '".md5($userData['password'])."')";
       $result = dbconfig::run($query);
       if(!$result) {
         throw new exception("Error to create new user.");
       }       
       $data = array('status'=>'success', 'msg'=>"You have been registered successfully login now.", 'result'=>'');
      }
     } catch (Exception $e) {
       $data = array('status'=>'error', 'msg'=>$e->getMessage());
     } finally {
        return $data;
     }
   }
 
  
   public static function checkUserExist($username) {
     try {
       $query = "SELECT username FROM users WHERE username = '".$username."'";
       $result = dbconfig::run($query);
       if(!$result) {
         throw new exception("Error in query!");
       }
       $count = mysqli_num_rows($result); 
       if($count>0) {
          throw new exception("Username already exist.");
       }       
       $data = array('status'=>'success', 'msg'=>"", 'result'=>'');
     } catch (Exception $e) {
      echo  $data = array('status'=>'error', 'msg'=>$e->getMessage()); 
     } finally {
        return $data;
     }
   }
 

   public static function checkUser($username, $password) {
     try {
       $query = "SELECT username FROM users WHERE username = '".$username."' and password = '".md5($password)."'";
       $result = dbconfig::run($query);
       if(!$result) {
         throw new exception("Error in query!");
       }
       $count = mysqli_num_rows($result); 
       if($count == 0) {
          throw new exception("Username/Password is incorrect.");
       }        
       $data = array('status'=>'success', 'msg'=>"", 'result'=>'');
     } catch (Exception $e) {
      echo  $data = array('status'=>'error', 'msg'=>$e->getMessage()); 
     } finally {
        return $data;
     }
   }
 
  
   public static function login($username, $password) {
     try {
        $check = self::checkUser($username, $password);
       if($check['status'] == 'error') {
       $data = $check;
       } else {
       $query = "SELECT id FROM users WHERE username = '".$username."' AND password = '".md5($password)."'";
       $result = dbconfig::run($query);
       if(!$result) {
         throw new exception("Error in query!");
       }
       $resultSet = mysqli_fetch_assoc($result);         
       $data = array('status'=>'success', 'msg'=>"User detail fetched successfully.", 'result'=>$resultSet);
      }
     } catch (Exception $e) {
       $data = array('status'=>'error', 'msg'=>$e->getMessage());
     } finally {
        return $data;
     }
   }
 
  
  public static function getUserById($id) {
     try {
       $query = "SELECT * FROM users WHERE id=".$id;
       $result = dbconfig::run($query);
       if(!$result) {
         throw new exception("Error in query");
       }
       $resultSet = mysqli_fetch_assoc($result); 
       $data = array('status'=>'success', 'tp'=>1, 'msg'=>"User detail fetched successfully", 'result'=>$resultSet);
     } catch (Exception $e) {
       $data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
     } finally {
        return $data;
     }
   }
 
}

Step:6- Now time to create all views pages like login, registration and profile page.




Fist we’ll create common header and footer part of all the pages.

header.php

<?php 
error_reporting(0);
session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PHP Auth</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>

footer.php

<?php 
if(isset($_SESSION['msg'])) { unset($_SESSION['msg']); } ?>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</body>
</html>

Index page will be your landing page. Don’t forget to include header and footer part in your all pages.

index.php

<?php include_once('header.php'); 
session_start();
if(!empty($_SESSION['result']['id'])) {
header('location:profile.php');
}
?>
<div class="panel panel-primary" style="width:35%;margin:0 auto; margin-top:2%">
<div class="panel-heading"><h3>User Login</h3></div>
<div class="panel-body" style="height:40%; text-align:center;" >
<p class="bg-info" id="msg"><?php echo (isset($_SESSION['msg'])) ? $_SESSION['msg'] : ''; ?></p>
 <form class="form-horizontal" role="form" id="loginForm" method="post" action="function.php?type=login">
  <div class="form-group">
    <label class="control-label col-sm-3" for="username">Username:</label>
    <div class="col-sm-9">
      <input type="email" class="form-control" name="username" placeholder="Enter username/emailid" required="required">
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-3" for="password">Password:</label>
    <div class="col-sm-9">
      <input type="password" class="form-control" name="password" placeholder="Enter password" required="required">
    </div>
  </div>
 
  <div class="form-group">
 
      <button style="width:90%" id="send" class="btn btn-primary btn-lg" type="submit">
         <span class="glyphicon glyphicon-send" ></span> Login
      </button>
 
      <a href="register.php" class="btn btn-primary btn-lg" style="width:90%; margin-top:5px;">
         <span class="glyphicon glyphicon-user" ></span> Register Now
      </a>
 
  </div>
</form>
</div>
</div>
 <?php include_once('footer.php'); ?>

register.php

<?php include_once('header.php'); 
?>
<div class="panel panel-primary" style="width:35%;margin:0 auto; margin-top:2%">
<div class="panel-heading"><h3>User Registration</h3></div>
<div class="panel-body" style="height:40%; text-align:center;" >
<p class="bg-info" id="msg"><?php echo (isset($_SESSION['msg'])) ? $_SESSION['msg'] : ''; ?></p>
 <form class="form-horizontal" role="form" id="signupForm" method="post" action="function.php?type=signup">
 <div class="form-group">
    <label class="control-label col-sm-3" for="name">Name:</label>
    <div class="col-sm-9">
      <input type="text" class="form-control" name="name" placeholder="Enter your name." required="required">
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-3" for="username">Username:</label>
    <div class="col-sm-9">
      <input type="email" class="form-control" name="username" placeholder="Enter your username/emailid." required="required">
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-3" for="password">Password:</label>
    <div class="col-sm-9">
      <input type="password" class="form-control" name="password" placeholder="Enter your password." required="required">
    </div>
  </div>
 
  <div class="form-group">
 
      <button style="width:90%" id="send" class="btn btn-primary btn-lg" type="submit">
         <span class="glyphicon glyphicon-user" ></span> Register
      </button>
 
      <a href="index.php" class="btn btn-primary btn-lg" style="width:90%; margin-top:5px;">
         <span class="glyphicon glyphicon-home" ></span> Home Page
      </a>
 
  </div>
</form>
</div>
</div>
 <?php include_once('footer.php'); ?>

This page will appear after user successfully logged-in.

profile.php

<?php session_start(); ?>
<!DOCTYPE html>
<?php include_once('header.php');  
require_once('classes/userClass.php');
$userObj = new USER();
$userInfo = $userObj->getUserById($_SESSION['result']['id']);
//echo ""; print_r($userInfo); exit;
 ?>
<div class="panel panel-primary" style="width:35%;margin:0 auto; margin-top:2%">
<div class="panel-heading"><h3>User Profile</h3></div>
<div class="panel-body" style="height:40%; text-align:center;" >
<p class="bg-info" id="msg"></p>
 <form class="form-horizontal" role="form" id="signupForm" method="post" action="function.php?formType=signup">
 <div class="form-group">
    <label class="control-label col-sm-3" for="name">Name:</label>
    <div class="col-sm-9">
     <?php echo $userInfo['result']['name']; ?>
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-3" for="username">Username:</label>
    <div class="col-sm-9">
      <?php echo $userInfo['result']['username']; ?>
    </div>
  </div>
 <div class="form-group">
    <label class="control-label col-sm-3" for="password">Password:</label>
    <div class="col-sm-9">
      <?php echo $userInfo['result']['password']; ?>
    </div>
  </div>
  <div class="form-group">
      <a href="function.php?type=logout" class="btn btn-primary btn-lg" style="width:90%; margin-top:5px;">
         <span class="glyphicon glyphicon-home" ></span> Logout
      </a>
  </div>
</form>
</div>
</div>
<?php include_once('footer.php'); ?>

Step:7- After successfully creation of all views pages create one more file function.php which will handle all your form and link request.

function.php

<?php
require_once('classes/userClass.php'); 
$userObj = new USER(); 
session_start();
$type = $_GET['type'];
 
if(empty($type) || !isset($type)) {
 
  echo 'Request type is not set';
 
} else if($type == 'signup') {
 
   $data =  USER::addNewUser($_REQUEST);
   $_SESSION = $data;
   if($data['status'] == 'error') {
     header("location:register.php");
   } else {
     header("location:index.php");
   }
} else if($type == 'login') {
   $username = addslashes($_REQUEST['username']);
   $password = addslashes($_REQUEST['password']);
   $_SESSION =  USER::login($username, $password);
   if($_SESSION['status'] == 'error') {
     header("location:index.php");
   } else {
     header("location:profile.php");
   }
 
} else if($type == 'logout') {
 unset($_SESSION);
 session_destroy();
 header("location:index.php");
}
 
?>

If you have setup all the steps successfully run your application on browser and enjoy..

You can see live working demo by clicking on the demo button and download source code, After that you can make changes according to your need..

Cheers 🙂

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.

Keywords: Signin and Signup form source code in php, Login and registration tutorial with code in php, How to create login and registration form in php, Download Signin and Signup form in php and mysql