Please support us by disabling ad blocker for smarttutorials.net ...

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 Bootstra. 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.

--
-- Database: `login`
--
CREATE DATABASE IF NOT EXISTS `login` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `login`;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(60) NOT NULL,
  `password` varchar(60) NOT NULL,
  `social_id` varchar(100) NOT NULL,
  `picture` varchar(250) NOT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `email` (`email`),
  KEY `login` (`password`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

Step 2:

 

 

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

<?php
/**
@author muni
@copyright http:www.smarttutorials.net
 */

require_once 'messages.php';

//site specific configuration declartion
define( 'BASE_PATH', 'http://localhost/user_login/');
define( 'DB_HOST', 'localhost' );
define( 'DB_USERNAME', 'root');
define( 'DB_PASSWORD', '');
define( 'DB_NAME', 'user_login');

function __autoload($class)
{
	$parts = explode('_', $class);
	$path = implode(DIRECTORY_SEPARATOR,$parts);
	require_once $path . '.php';
}

where __autoload() is one of the magic function of PHP5. If I want to use some classes in some other php file, we must include that class file using require_once or include_once to use functions of that class. If I want to 100 classes in particular php file, then I need wrtite 100 require_once statements in that file to use right. Here where that magic __autoload() function helps us to load 100 classes without writing 100 require_once statements at the start of the file. This magic __autoload function will called whenever we initalize PHP classes and add that PHP classes to that file.

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_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('PASSOWRD_CHANAGE_SUCCESS', 'Password changed successfully.');

Now create DBclass.php and create DBclass in it.

<?php
class Cl_DBclass
{
	/**
	 * @var $con will hold database connection
	 */
	public $con;

	/**
	 * This will create Database connection
	 */
	public function __construct()
	{
		$this->con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
		if( mysqli_connect_error()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
	}
}

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

Step 3:

Create User.php file, which going to handle all the php realted 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
 * @copyright www.smarttutorials.net
 */
class Cl_User
{
	/**
	 * @var will going contain database connection
	 */
	protected $_con;

	/**
	 * it will initalize DBclass
	 */
	public function __construct()
	{
		$db = new Cl_DBclass();
		$this->_con = $db->con;
	}

	/**
	 * 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:
			$trimmed_data = array_map('trim', $data);

			// escape variables for security
			$name = mysqli_real_escape_string( $this->_con, $trimmed_data['name'] );
			$password = mysqli_real_escape_string( $this->_con, $trimmed_data['password'] );
			$cpassword = mysqli_real_escape_string( $this->_con, $trimmed_data['confirm_password'] );

			// Check for an email address:
			if (filter_var( $trimmed_data['email'], FILTER_VALIDATE_EMAIL)) {
				$email = mysqli_real_escape_string( $this->_con, $trimmed_data['email']);
			} else {
				throw new Exception( "Please enter a valid email address!" );
			}

			if((!$name) || (!$email) || (!$password) || (!$cpassword) ) {
				throw new Exception( FIELDS_MISSING );
			}
			if ($password !== $cpassword) {
				throw new Exception( PASSWORD_NOT_MATCH );
			}
			$password = md5( $password );
			$query = "INSERT INTO users (user_id, name, email, password, created) VALUES (NULL, '$name', '$email', '$password', CURRENT_TIMESTAMP)";
			if(mysqli_query($this->_con, $query))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 ) ){

			// Trim all the incoming data:
			$trimmed_data = array_map('trim', $data);

			// escape variables for security
			$email = mysqli_real_escape_string( $this->_con,  $trimmed_data['email'] );
			$password = mysqli_real_escape_string( $this->_con,  $trimmed_data['password'] );

			if((!$email) || (!$password) ) {
				throw new Exception( LOGIN_FIELDS_MISSING );
			}
			$password = md5( $password );
			$query = "SELECT user_id, name, email, created FROM users where email = '$email' and password = '$password' ";
			$result = mysqli_query($this->_con, $query);
			$data = mysqli_fetch_assoc($result);
			$count = mysqli_num_rows($result);
			if( $count == 1){
				$_SESSION = $data;
				$_SESSION['logged_in'] = true;
				return true;
			}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:
			$trimmed_data = array_map('trim', $data);

			// escape variables for security
			$password = mysqli_real_escape_string( $this->_con, $trimmed_data['password'] );
			$cpassword = $trimmed_data['confirm_password'];
			$user_id = mysqli_real_escape_string( $this->_con, $trimmed_data['user_id'] );

			if((!$password) || (!$cpassword) ) {
				throw new Exception( FIELDS_MISSING );
			}
			if ($password !== $cpassword) {
				throw new Exception( PASSWORD_NOT_MATCH );
			}
			$password = md5( $password );
			$query = "UPDATE users SET password = '$password' WHERE user_id = $user_id";
			if(mysqli_query($this->_con, $query))return true;
		} else{
			throw new Exception( FIELDS_MISSING );
		}
	}

	/**
	 * This handle sign out process
	 */
	public function logout()
	{
		session_unset();
		session_destroy();
		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 )
	{
		if( !empty( $data ) ){

			// escape variables for security
			$email = mysqli_real_escape_string( $this->_con, trim( $data['email'] ) );

			if((!$email) ) {
				throw new Exception( FIELDS_MISSING );
			}
			$password = $this->randomPassword();
			$password1 = md5( $password );
			$query = "UPDATE users SET password = '$password1' WHERE email = $email";
			if(mysqli_query($this->_con, $query)){
				$to = $email;
				$subject = "New Password Request";
				$txt = "Your New Password ".$password;
				$headers = "From: admin@smarttutorials.net" . "\r\n" .
						"CC: admin@smarttutorials.net";

				mail($to,$subject,$txt,$headers);
				return true;
			}
		} else{
			throw new Exception( FIELDS_MISSING );
		}
	}

	/**
	 * 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
	}
}

where array_map(), trim() and mysqli_real_escape_string() which helps us secure malicious database attack..

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] muni[at]smarttutorials.net

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.

  • Mike

    Is this free to use on a commercial website?

  • Yes…. you can use mike…..

  • Akhilesh Patel

    login_part1 script is not working like registration page………

  • User

    seems forgot password not working

  • Sorry can you elaborate little bit..

  • Seems to working for me ..

  • 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

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

  • 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 )

  • 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 ).

  • 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

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

  • 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

  • User

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

  • 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

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

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

  • 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

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

  • User

    ok

  • User

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

  • 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…

  • User

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

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

  • 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

  • Are you working in localhost?….

  • Akhilesh Patel

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

  • 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 audleywalker1@gmail.com

  • Oktay KOCATÜRK

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

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

  • 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

  • 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…

  • Naor Czerwacki

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

  • SANTANU ADAK

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

  • SANTANU ADAK

    yes

  • Gagandeep Sharma

    Hi Muni,

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

  • 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.

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

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

  • 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.

  • Check your mail… I have sent download link to your mail…

  • DecodeIndia India

    I have not received the download link

  • check your mail link sent..

  • alien on board

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

  • 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.

  • Ravindra Athreya

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

  • Snowtek TV

    Hey bro, I haven’t got the files yet. 🙁

  • sent…

  • Will this Protect from Hackers/SQL Injections?

  • 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,

  • Ella Sherilyn Ramos

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

  • Thought to update… Will update in next release

  • Ella Sherilyn Ramos

    (y)

  • 🙂

  • Seph

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

  • bbutter

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

  • qdesigner

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

  • qdesigner

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

  • 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

  • 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.

  • Anthony

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

  • Rogerio Jesus

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

  • 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

  • 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.

Get Instant Script Download Access!