User registration and Login Using PHP5, MySQLi, jQuery and Bootstrap

Posted by & filed under CSS, HTML5, JQUERY, MYSQL, PHP.

In this tutorial we are going to see simple User registration, Login and Forget password functionality using PHP5 object oriented programming, MySQLi, jQuery and Bootstrap. As well it has templating system that’s after login pages (home.php, going.php and lesson.php) will template pages like (header.php, footer.php and sidebar.php). It has six pages

1. Login page

2. Registeration page

3. Forget password page

4. Home page

and two more pages.

User registration, Login and forget password Using PHP5, MySqli, jQuery and Bootstrap

User registration, Login and forget password Using PHP5, MySqli, jQuery and Bootstrap

 

 

Step 1:

Create sample Database and tables for this tutorial with the following SQL queries.

CREATE TABLE `user` (
  `user_id` int(10) UNSIGNED NOT NULL,
  `name` varchar(75)  NOT NULL,
  `email` varchar(150)  NOT NULL,
  `password` varchar(150)  NOT NULL,
  `social_id` varchar(100)  DEFAULT NULL,
  `picture` varchar(500)  DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  `uuid` varchar(75) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `user`
  ADD PRIMARY KEY (`user_id`),
  ADD KEY `email` (`email`),
  ADD KEY `password` (`password`);


ALTER TABLE `user`
  MODIFY `user_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
COMMIT;

Step 2:

 

 

Create config.php file and define general configuration related informations in it.

<?php
/**
 * File config.php
 * @author muni
 * @link https://smarttutorials.net/
 */
ob_start();
session_start();
require_once 'messages.php';

//site specific configuration declartion
define('BASE_PATH', 'http://localhost/demo_tut/user_login/');
define('DB_HOST', 'localhost');
define('DB_NAME', 'smarttut_demo');
define('DB_USER','xyz');
define('DB_PASSWORD','mysql');
define('ADS_ENABLE', false);


// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
    $parts = explode('_', $class);
	$path = implode(DIRECTORY_SEPARATOR,$parts);
	require_once $path . '.php';
});

where spl_autoload_register() – Register given function as __autoload() implementation.

This function help us programmatically autoload php classes during PHP Object initialization. This prevents manual effort of importing PHP file using require/require_once or include/include_once.

Now create messages.php file, that will have all the success and error message.

<?php
define('FIELDS_MISSING', 'Some Fields Are Missing');
define('PASSWORD_NOT_MATCH', 'Passwords do not match');
define('USER_REGISTRATION_FAIL', 'User registration failed');
define('USER_NOT_EXISTS', 'User is not exists in our system');
define('USER_REGISTRATION_SUCCESS', 'User registration was successful, You may login now');


define('LOGIN_FIELDS_MISSING', 'Email and Password are missing');
define('LOGIN_FAIL', 'Email and Password are mismatch');
define('LOGOUT_SUCCESS', 'You are logged out successfully.');

define('PASSOWRD_CHANAGE_SUCCESS', 'Password changed successfully.');
define('OLD_PASSOWRD_NOT_MATCHING', 'Old Password is not matching with our records.');
define('OLD_PASSOWRD_AND_NEW_MATCHING', 'Old & New Passwords are same, Please different new password.');
define('MAIN_TITLE', "Smart Login System");

define('PHP_MAIN_TITLE', 'Login System Using PHP, MySQL & jQuery');
define('EMAIL_NOT_EXISTS', 'Email is not exists in our system');
define('SOMETHING_WENT_WRONG', 'Something went wrong please try again later.');

Now create DBclass.php file inside Cl folder, next create Cl_DBclass in it.

<?php
class Cl_DBclass
{
	/**
	 * @var $mysqli will hold database connection
	 */
	public $mysqli;
	
	/**
	 * This will create Database connection
	 */
	public function __construct()
	{
		$this->mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

		if ($this->mysqli->connect_errno) {
			echo "Failed to connect to MySQL: " . $this->mysqli -> connect_error;
			exit();
		}

		// $sql = "SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))";
		// $this->mysqli->query($sql);
	}


	/**
	 * Preparing Statement
	 */
	function prepareStatement($sql, $params = null)
	{
		$stmt = $this->mysqli->prepare($sql);
		if (!($stmt)) {
			throw new Exception("Prepare failed: (" . $this->mysqli->errno . ") " . $this->mysqli->error);
		}

		if (!empty($params) && is_array($params)) {
			foreach ($params as $key => $param) {
				$params[$key] = $this->mysqli->real_escape_string($param);
			}

			$count = count($params);            
			$bindStr = str_repeat('s', $count);
			$stmt->bind_param($bindStr, ...$params);
		}

		if (!$stmt->execute()) {
			throw new Exception("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
		}

		return $stmt;
	}

	/**
	 * GetResult
	 */
	function getResult($stmt)
	{
		if (!($res = $stmt->get_result())) {
			throw new Exception("Getting result set failed: (" . $stmt->errno . ") " . $stmt->error);
		}
		return $res;
	}
}

whenever we initialize DBclass, it’s __construct function will be called and creates DB connection.

Step 3:

Create User.php file, which going to handle all the php related logic functionalities. while we going to save any data to database it’s validates posted data, once it passess validation then it saves posted data to Database. If it fails validation it throughs the error Exception.

<?php
/**
 * This User will have functions that hadles user registeration,
 * login and forget password functionality
 * @author muni
 * @link https://smarttutorials.net/
 * @copyright www.smarttutorials.net
 */
class Cl_User
{
	
	private $_db;
	/**
	 * it will initalize DBclass
	 */
	public function __construct()
	{
		$this->_db = new Cl_DBclass();
	}
	
	/**
	 * this will handles user registration process
	 * @param array $data
	 * @return boolean true or false based success 
	 */
	public function registration( array $data )
	{
		if (!empty($data)) {
			// Trim all the incoming data:
			$data = array_map('trim', $data);		
			// Check for an email address:
			if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
				throw new Exception( "Please enter a valid email address!" );
			} 
		
			if ((!$data['name']) || (!$data['email']) || (!$data['password']) || (!$data['confirm_password']) ) {
				throw new Exception(FIELDS_MISSING);
			}
			if ($data['password'] !== $data['confirm_password']) {
				throw new Exception(PASSWORD_NOT_MATCH);
			}

			$password = Cl_Utilities::hash_password($data['password']);
			$uuid = uniqid('', true);

			$sql = "INSERT INTO user (user_id, name, email, password, created, uuid) 
			VALUES (NULL, ?, ?, ?, CURRENT_TIMESTAMP, '$uuid')";

			$this->_db->prepareStatement($sql, [$data['name'], $data['email'], $password]);
			return true;
		} else{
			throw new Exception(USER_REGISTRATION_FAIL);
		}
	}
	/**
	 * This method will handle user login process
	 * @param array $data
	 * @return boolean true or false based on success or failure
	 */
	public function login( array $data )
	{
		$_SESSION['logged_in'] = false;
		if (!empty($data)){
			$data = array_map('trim', $data);
			if ((!$data['email']) || (!$data['password'])) {
				throw new Exception(LOGIN_FIELDS_MISSING);
			}
			
			$sql = "SELECT user_id, name, email, password, created FROM user where email =?";
			$stmt = $this->_db->prepareStatement($sql, [$data['email']]);
			$res = $this->_db->getResult($stmt);
			$result =  $res->fetch_assoc();
			

			$count = count($result);
			if ($count >= 1){
				if (Cl_Utilities::verify_password($data['password'], $result['password'])) {
					unset($result['password']);
					$_SESSION = $result;
					$_SESSION['logged_in'] = true;
					return true;
				} else {
					throw new Exception(PASSWORD_NOT_MATCH);
				}
			}else{
				throw new Exception(LOGIN_FAIL);
			}
		} else{
			throw new Exception(LOGIN_FIELDS_MISSING);
		}
	}
	
	
	/**
	 * This will shows account information and handles password change
	 * @param array $data
	 * @throws Exception
	 * @return boolean
	 */
	
	public function account( array $data )
	{
		if(!empty($data) ){
			// Trim all the incoming data:
			$data = array_map('trim', $data);
			if ((!$data['password']) || (!$data['confirm_password'])) {
				throw new Exception(FIELDS_MISSING);
			}
			if ($data['password'] !== $data['confirm_password']) {
				throw new Exception(PASSWORD_NOT_MATCH);
			}
			if ($data['password'] == $data['old_password']) {
				throw new Exception(OLD_PASSOWRD_AND_NEW_MATCHING);
			}
			$this->verifyOldPassword($data['old_password'], $data['user_id']);

			$password = Cl_Utilities::hash_password($data['password']);
			$query = "UPDATE user SET password = ? WHERE user_id = ?";
			$this->_db->prepareStatement($query, [$password, $data['user_id']]);
			return true;
		} else{
			throw new Exception(FIELDS_MISSING);
		}
	}

	/**
	 * Verify Old Password
	 */
	private function verifyOldPassword($old_password, $user_id)
	{
		$sql = "select user_id, password from user WHERE user_id = ?";
		$stmt = $this->_db->prepareStatement($sql, [$user_id]);
		$res = $this->_db->getResult($stmt);
		$result =  $res->fetch_assoc();
		if (empty($result)) {
			throw new Exception(USER_NOT_EXISTS);
		}
		if (Cl_Utilities::verify_password($old_password, $result['password'])) {
			return true;
		}
		throw new Exception(OLD_PASSOWRD_NOT_MATCHING);	
	}
	
	/**
	 * This handle sign out process
	 */
	public function logout()
	{
		session_unset();
		session_destroy();
		unset($_SESSION['oauth_token']);
		unset($_SESSION['oauth_token_secret']);

		session_start();
		$_SESSION['success'] = LOGOUT_SUCCESS;
		header('Location: index.php');
	}
	
	/**
	 * This reset the current password and send new password to mail
	 * @param array $data
	 * @throws Exception
	 * @return boolean
	 */
	public function forgetPassword( array $data )
	{
		try {
			if (!empty($data)) {
				$data = array_map('trim', $data);
				if (!$this->checkEmailExists($data['email'])) {
					throw new Exception(EMAIL_NOT_EXISTS);
				}
	
				$password = $this->randomPassword();
				$password1 = Cl_Utilities::hash_password($password);	
	
				$sql = "UPDATE user SET password =? WHERE email =?";

				$this->_db->prepareStatement($sql, [$password1, $data['email']]);
	
				$options = [
					'to' => $data['email'],
					'subject' => "New Password Request",
					'body' => "Your New Password ".$password
				];
				Cl_SmartMailer::sendMail($options);
				return true;
			} else{
				throw new Exception(FIELDS_MISSING);
			}
		} catch (Exception $e) {
			throw new Exception(SOMETHING_WENT_WRONG);
		}
		
	}

	private function checkEmailExists($email)
	{
		$sql = "select user_id from user where email=?";
		$stmt = $this->_db->prepareStatement($sql, [$email]);
		$res = $this->_db->getResult($stmt);
		return $res->num_rows;
	}
	
	/**
	 * This will generate random password
	 * @return string
	 */
	
	private function randomPassword() {
		$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
		$pass = array(); //remember to declare $pass as an array
		$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
		for ($i = 0; $i < 8; $i++) {
			$n = rand(0, $alphaLength);
			$pass[] = $alphabet[$n];
		}
		return implode($pass); //turn the array into a string
	}
	
	
	
	public function pr($data = ''){
		echo "<pre>"; print_r( $data ); echo "</pre>";
	}
}

where array_map() & trim() – functions will remove white spaces in the data.

Step 4:

Next create Utilities.php file and add the following scripts in it. This Cl_Utilities class will hash and verify the password using hash_password & verify_password functions.

<?php

class Cl_Utilities 
{
    private static $password_options = [
        'cost' => 12,
    ];
    /**
     * Hash Password
     */
    public static function hash_password($password)
    {
        return password_hash($password, PASSWORD_BCRYPT, static::$password_options);
    }

    /**
     * Hash Password
     */
    public static function verify_password($password, $hash)
    {
        return password_verify($password, $hash);
    }
}

Step 5:

Finally create SmartMailer.php file and add the following scripts in it. This file will take care of send mail using PHP mail() function.

<?php
/**
 * File SmartMailer.php
 * @author muni
 * @link https://smarttutorials.net/
 */

class Cl_SmartMailer
{
    public static function sendMail($options =[]){
        if (empty($options)) {
            return false;
        }
        $to = $options['to'] ? $options['to'] : '';
        $subject = $options['subject'] ? $options['subject'] : '';
        $body = $options['body'] ? $options['body'] : '';

        $headers = "From: admin@smarttutorials.net" . "\r\n" .
                "CC: admin@smarttutorials.net";
            
        mail($to, $subject, $body, $headers);
    }
}

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni2explore[at]gmail.com

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

%d bloggers like this:

Get Instant Script Download Access!