Simple OOPS based login and registration script in php and mysql

php-auth

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


class dbconfig {
  // database hostname 
  protected static $host = "localhost";
  // database username
  protected static $username = "root";
  // database password
  protected static $password = "root";
  //database name
  protected static $dbname = "php-auth";
 
  static $con;
 
  function __construct() {
    self::$con = self::connect(); 
  }
 
  // open connection
  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();
     } 
  }
 
 // close connection
  public static function close() {
     mysqli_close(self::$con);
  }
 
// run query
  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


/*
* Author: Rohit Kumar
* Website: iamrohit.in
* Version: 0.0.1
* Date: 27-09-2015
* App Name: PHP-Auth
* Description: Simple oops based login and registration script with exceptional handling in php and mysql.
*/
require_once("dbconfig.php");
class USER extends dbconfig {
 
   public static $data;
 
   function __construct() {
     parent::__construct();
   }
 
 // Create new user/signup
   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;
     }
   }
 
  // Check if user already exist
   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;
     }
   }
 
// Check if username/password is incorrect
   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;
     }
   }
 
  // login function
   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;
     }
   }
 
  // Get user information by userid
  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

 
error_reporting(0);
session_start(); ?>






PHP Auth





PHP Auth

footer.php

 
if(isset($_SESSION['msg'])) { unset($_SESSION['msg']); } ?>