, , , ,

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

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…

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

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: [email protected]" . "\r\n" .
                "CC: [email protected]";
            
        mail($to, $subject, $body, $headers);
    }
}

66 responses to “User registration and Login Using PHP5, MySQLi, jQuery and Bootstrap”

  1. Mike

    Is this free to use on a commercial website?

  2. Yes…. you can use mike…..

  3. Akhilesh Patel

    login_part1 script is not working like registration page………

  4. User

    seems forgot password not working

  5. Sorry can you elaborate little bit..

  6. Seems to working for me ..

  7. User

    i have changed this UPDATE users SET password = ‘$password1’ WHERE email = $email to UPDATE users SET password = ‘$password1’ WHERE email = ‘$email’ then only it worked for me

  8. Yes you are right… where email is string I missed apostrophe (”)… Thank you

  9. Guest

    and i have issues for oauth 2 facebook login, google login twitter login script.. i have same email id for facebook and google login. first i have registered with facebook .. then social id is stored in the database.. it logged in succesfully.. after that i tried with google + login with same email id.. it is not logging in ( I mean whether it will store 2 social ids for same email iD )

  10. User

    and i have issues for oauth 2 facebook login, google login twitter login script.. i have same email id for facebook and google login. first i have registered with facebook .. then social id is stored in the database.. it logged in succesfully.. after that i tried with google + login with same email id.. it is not logging in ( I mean whether it will store 2 social ids for same email iD ).

  11. User

    one more issue is when i register with facebook login . password is not stored in database right. it logged in successfully. but in myaccount page there is option to change password… where there we have to provide current password. i have checked in the database it is null. form validation does not accept null in that column. so i am not able to change my password in that case

  12. do one thing generate random password and insert at the time of registration….

  13. no… are you getting response from google oauth?… if yes print all the queries in google_login function and share with me…2 social ids never be the same

  14. User

    actually i gave forgot password and changed it or i will remove current password validation.

  15. User

    i mean facebook social id is already stored in database. then i logged with google.. which has same email id as facebook email. . so now google social id should store in the same column (social id column). at this time it is failing. whether it will replace the previous social id

  16. better generate random password and insert at the time of FB registration

  17. no it will insert int new row i.e. record.. better print insert query, and see what’s the issue

  18. User

    user will not know the generated random password right. so he need to give again forgot password to get that one. Ok will do

  19. you need to send email to user at the time registeration with his login details.

  20. User

    ok

  21. User

    UNIQUE KEY `email` (`email`), i think it will not insert another record . will check

  22. Yes… UNIQUE KEY will not allow to insert same email ID one more time.. I checked in my db UNIQUE KEY is not set for email ID…

    So please remove UNIQUE KEY constraint , it will solve your problem…

  23. User

    ya it solved. will test all cases. thanks for your time

  24. ok … Thank you… Please let me know if any issues….

  25. Chetan Soni

    Forget password seems to be not working for me, I Already added apostrophe like this ‘$email’
    But when i enter my email ID for recovering, Didn’t get any Error message and even i didn’t receive any mail

    Please help

  26. Are you working in localhost?….

  27. Akhilesh Patel

    yes it’s working fine………….good tutorials….thanks………

  28. Guest

    Hello Muni, I had purchased the Paid version of the ‘Responsive PHP Quiz Script’ about two weeks now. I had emailed you my issues, I can’t seem to create a user with the ‘Sign up’ field…. and I thought all I had to do after purchasing the software was to edit the ‘config.php’ file with my database credentials and create the database tables in mysql, I did that and the application is still not working. I tried manually creating the user account in the mysql database to login to the application and then I was able to login successfully. But I received another issue, All the navigation links are broken (to start the Quiz, to view the results, etc) ……Also after taking the quiz, the answers are not saving to the database. The free DEMO version is working like a charm on the same database, but it does not save the users submitted results to the database. Can you help me please!!!!…… My email is [email protected]

  29. Oktay KOCATรœRK

    Hi, why can’t I download source code of this tutorial??

  30. You need subscribe my blog, then we will send you download link after 12 hours .. Only first time.

  31. Kovu’Akpevwe EGBELUGHE

    Hi Muni,

    great tutorial by the way.

    I have a small issue, i get “Strict standards: Only variables should be passed by reference in C:wampwwwlogin_part1templatesheader.php on line 48” in the home.php page.

    Any suggestion on how i can fix this.

    Thanks

  32. Naor Czerwacki

    i liked it nicely done.. .the problem is that i subscribe but 12 hours have passed.. more like a day+ by now..
    i did get the email and i clicked on the link given which sent me to a feedburner site which displayed this message:

    ” Email Subscription Confirmed!
    A message will be delivered to (my email address) if the publisher has produced new content on that day. No new content, no email for you. ”

    this was on July 05, 2015 3:10:22 AM (my time)..
    this is the final piece for my project.. i will much appreciate it if you look in to it..
    thank you in advance…

  33. Naor Czerwacki

    i have the same problem.. did you manage to fix it?

  34. SANTANU ADAK

    Fatal error: Class ‘Cl_User’ not found in index.php

  35. SANTANU ADAK

    yes

  36. Gagandeep Sharma

    Hi Muni,

    how to handle this function call in “user.php” in Register.php

  37. You need to create object of the User class in Register.php file then using that object you may call functions of User class from Register.php file.

  38. Email not work in localhost, In order to email work in localhost you need to do some extra configuration.

  39. may be you are missing autoload function config.php file… This is because Class ‘Cl_User’is not included in the index.php file.

  40. Gagandeep Sharma

    Thanks Muni.. I figured that out at that time only. And also i have not received any link for download as i have subscribed yesterday 2PM and it is more than 12 hours now.

  41. Check your mail… I have sent download link to your mail…

  42. DecodeIndia India

    I have not received the download link

  43. check your mail link sent..

  44. alien on board

    Hi Muni. Great tutorial, I have subscribed. Could you send me a link to download the source? Thanks

  45. Bikila

    I don’t understand why I am not getting any response from you on a request to customize your codes, Muni. I sent several emails to the email addresses provided on the website but no response yet. Please let me know how to reach you.

  46. Ravindra Athreya

    Hi Muni,
    I have not received the download link, could you plz send it

  47. Snowtek TV

    Hey bro, I haven’t got the files yet. ๐Ÿ™

  48. Will this Protect from Hackers/SQL Injections?

  49. Hisham

    Dear,

    how can i add the option of adding a profile picture, and what’s the purpose of social_id ?

    also if you can help me add a function to update the last login time database field for every person i will be thankful.

    Thanks for the tutorial really nice like it !! ๐Ÿ™‚
    best regards,

  50. Ella Sherilyn Ramos

    How come you are not using prepared statements for your database transaction to avoid sql injections.

  51. Thought to update… Will update in next release

  52. Ella Sherilyn Ramos

    (y)

  53. Seph

    It’s been well over 15 hours now and still no email.

  54. bbutter

    Hi Muni, Can you tell me how to get user data form database to show on their account page?

  55. qdesigner

    Hi Muni,
    I have not received the download link, could you please send it.

  56. qdesigner

    Hi Muni,
    I have not received the download link, could you please send it.

  57. hai muni this is my first comment on your code blog first of thanks for this post its help me to understand the working of user management system with SQL i need help from i need this login system with email validation with email verification to the users…. thanks in advance

  58. Peter

    The user sign up page on the user-registration-and-login-using-php5-mysqli-jquery-and-bootstrap “register” page does not INSERT information into the database. Could you please advise? Thank you.

  59. Anthony

    Hi Muni.. pls send the source code in my email.. thanks

  60. Rogerio Jesus

    Thanks for the script, tested and worked well.
    Could anyone help me get admin level?

  61. sukumar paul

    Thank you sir ,it is really helpful to me.
    PDO tutorial are also very nice.
    I am waiting for your further more tutorials

  62. Hussein Al Sherbiny

    Hello Muni,

    great effort.

    how can i call the user’s name on my page, i mean what is the variable should i call for that.

  63. Eduard Aguilar

    ads.php require ?

  64. Jr Cole Syd

    hi muni.. i hope this is not coming late.. but its better late than never.. the registration button is no submitting.. likewise the login.. not entering data into database.. pls what can i do? you can check out the link pls.. http://www.abc.allwie.com nice tutorials tho..

Leave a Reply