Showing posts with label email verification. Show all posts
Showing posts with label email verification. Show all posts

Tuesday, 9 January 2024

Mastering User Registration and Email Verification in PHP with JWT Tokens: A Comprehensive Guide


In the ever-evolving landscape of web development, ensuring a secure and streamlined user registration process is paramount. One powerful way to enhance the security of your PHP-based applications is by implementing user registration and email verification using JSON Web Tokens (JWT). In this guide, we'll walk you through the process step by step, empowering you to bolster the authentication mechanisms of your PHP projects.


Mastering User Registration and Email Verification in PHP with JWT Tokens: A Comprehensive Guide


Understanding the Basics


What is JWT?


JSON Web Tokens (JWT) provide a secure and compact way to transmit information between parties. In the context of user authentication, JWTs can be used to securely store user data and ensure that information is not tampered with during transmission.

Why PHP?


PHP remains a popular server-side scripting language, particularly for web development. Its versatility, ease of use, and extensive community support make it an excellent choice for implementing robust authentication systems.

Step-by-Step Guide


1. Setting Up Your PHP Environment


Ensure that your PHP environment is configured correctly. This includes setting up a database to store user information securely.


CREATE TABLE `user` (
  `user_id` int NOT NULL AUTO_INCREMENT,
  `user_email` varchar(70) DEFAULT NULL,
  `user_password` varchar(45) DEFAULT NULL,
  `user_name` varchar(45) DEFAULT NULL,
  `email_verification_status` enum('Not Verified','Verified') DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

INSERT INTO `user` VALUES (1,'johnsmith@gmail.com','password','John Smith','Verified'),(16,'peterparker@mailinator.com','password','Peter Parker','Verified'),(17,'donna@mailinator.com','password','Donna Hubber','Verified'),(18,'mike@mailinator.com','password','Mike','Verified');


2. Integrating JWT Library


Choose a reliable JWT library for PHP, such as Firebase JWT. Integrate it into your project to start creating and validating JWTs.


composer require firebase/php-jwt


3. User Registration


Implement a user registration system that securely stores user data in your database. Hash passwords using strong encryption algorithms to enhance security.

4. Generating JWTs


Upon successful registration, generate a JWT containing relevant user information. This token will serve as a secure means of verifying the user's identity in subsequent requests.

5. Email Verification


Send a verification email containing a link with a JWT to the user's registered email address. This link will confirm the user's identity and activate their account.

6. Token Validation


Implement a mechanism to validate JWTs in subsequent user requests. This ensures that only authenticated users can access protected resources.

Best Practices and Security Measures


1. Use HTTPS


Ensure your application is served over HTTPS to encrypt data transmitted between the user and the server, preventing man-in-the-middle attacks.

2. Token Expiry


Set a reasonable expiration time for your JWTs to mitigate the risk of unauthorized access.

3. Secure Database Storage


Employ secure practices for storing user data in the database, such as hashing and salting passwords.

4. Rate Limiting


Implement rate limiting to prevent brute-force attacks on the authentication system.

Conclusion


By following this comprehensive guide, you'll be well-equipped to implement a robust user registration and email verification system using PHP and JWT. Enhance the security of your applications, protect user data, and provide a seamless experience for your users. Stay ahead in the world of web development by mastering the art of authentication with PHP and JWT tokens.





Source Code


register.php

<?php 

//register.php

require 'vendor/autoload.php';

use Firebase\JWT\JWT;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$error = '';

$message = '';

if(isset($_POST['register']))
{
	$connect = new PDO("mysql:host=localhost; dbname=testing", "root", "password");

	if(empty($_POST['name']))
	{
		$error = 'Please Enter Name Details';
	}
	else if(empty($_POST['email']))
	{
		$error = 'Please Enter Email Details';
	}
	else if(empty($_POST['password']))
	{
		$error = 'Please Enter Password Details';
	}
	else
	{
		$query = "SELECT user_id FROM user WHERE user_email = ?";
		$statement = $connect->prepare($query);
		$statement->execute([$_POST["email"]]);
		if($statement->rowCount() > 0)
		{
			$error = 'Email Alaready Exists';
		}
		else
		{
			$data = array(
				':user_email'		=>	trim($_POST['email']),
				':user_password'	=>	trim($_POST['password']),
				':user_name'		=>	trim($_POST['name']),
				':email_verification_status'	=>	'Not Verified'
			);

			$insertQuery = "INSERT INTO user (user_email, user_password, user_name, email_verification_status) VALUES (:user_email, :user_password, :user_name, :email_verification_status)";
			$statement = $connect->prepare($insertQuery);
			if($statement->execute($data))
			{
				$key = '1a3LM3W966D6QTJ5BJb9opunkUcw_d09NCOIJb9QZTsrneqOICoMoeYUDcd_NfaQyR787PAH98Vhue5g938jdkiyIZyJICytKlbjNBtebaHljIR6-zf3A2h3uy6pCtUFl1UhXWnV6madujY4_3SyUViRwBUOP-UudUL4wnJnKYUGDKsiZePPzBGrF4_gxJMRwF9lIWyUCHSh-PRGfvT7s1mu4-5ByYlFvGDQraP4ZiG5bC1TAKO_CnPyd1hrpdzBzNW4SfjqGKmz7IvLAHmRD-2AMQHpTU-hN2vwoA-iQxwQhfnqjM0nnwtZ0urE6HjKl6GWQW-KLnhtfw5n_84IRQ';

				$payload = array(
					'email'		=>	trim($_POST['email'])
				);

				$token = JWT::encode($payload, $key, 'HS256');

				$verificationLink = 'http://localhost/tutorial/php-jwt-login/verify.php?token='.$token;

				$mail = new PHPMailer(true);
				$mail->isSMTP();
				$mail->Host = 'smtp.gmail.com';
				$mail->SMTPAuth = true;
				$mail->Username = 'your gmail address';
				$mail->Password = 'xxx'; //Here you have to define your gmail password
				$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
				$mail->Port = 587;
				$mail->setFrom('sender@email.com', 'sender@email.com');
				$mail->addAddress(trim($_POST['email']), trim($_POST['name']));
				$mail->isHTML(true);
				$mail->Subject = 'Verify Your Email Address';
				$mail->Body = '
				<p>Hi,</p>
			    <p>Thank you for registering with us! To complete your registration and activate your account, please click on the following link:</p>
			    <p><a href="'.$verificationLink.'">'.$verificationLink.'</a></p>
			    <p>Thank you,<br />Webslesson.info</p>
				';
				$mail->send();
				$message = 'Verification eMail has been send! Registration Complete!';
			}
		}
	}
}

?>

<!doctype html>
<html lang="en">
  	<head>
    	<!-- Required meta tags -->
    	<meta charset="utf-8">
    	<meta name="viewport" content="width=device-width, initial-scale=1">

    	<!-- Bootstrap CSS -->
    	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    	<title>PHP Registration & Email Validation using JWT Token</title>
  	</head>
  	<body>
    	<div class="container">
    		<h1 class="text-center mt-5 mb-5">PHP Registration & Email Validation using JWT Token</h1>
    		<div class="row">
    			<div class="col-md-4">&nbsp;</div>
    			<div class="col-md-4">
    				<?php

    				if($error !== '')
    				{
    					echo '<div class="alert alert-danger">'.$error.'</div>';
    				}

    				if($message !== '')
    				{
    					echo '<div class="alert alert-success">'.$message.'</div>';
    				}

    				?>
		    		<div class="card">
		    			<div class="card-header">Register</div>
		    			<div class="card-body">
		    				<form method="post">
		    					<div class="mb-3">
			    					<label>Name</label>
			    					<input type="text" name="name" class="form-control" />
			    				</div>
			    				<div class="mb-3">
			    					<label>Email</label>
			    					<input type="email" name="email" class="form-control" />
			    				</div>
			    				<div class="mb-3">
			    					<label>Password</label>
			    					<input type="password" name="password" class="form-control" />
			    				</div>
			    				<div class="text-center">
			    					<input type="submit" name="register" value="Register" class="btn btn-primary" />
			    				</div>
		    				</form>
		    			</div>
		    		</div>
		    	</div>
	    	</div>
    	</div>
  	</body>
</html>


verify.php

<?php

//verify.php

require 'vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$key = '1a3LM3W966D6QTJ5BJb9opunkUcw_d09NCOIJb9QZTsrneqOICoMoeYUDcd_NfaQyR787PAH98Vhue5g938jdkiyIZyJICytKlbjNBtebaHljIR6-zf3A2h3uy6pCtUFl1UhXWnV6madujY4_3SyUViRwBUOP-UudUL4wnJnKYUGDKsiZePPzBGrF4_gxJMRwF9lIWyUCHSh-PRGfvT7s1mu4-5ByYlFvGDQraP4ZiG5bC1TAKO_CnPyd1hrpdzBzNW4SfjqGKmz7IvLAHmRD-2AMQHpTU-hN2vwoA-iQxwQhfnqjM0nnwtZ0urE6HjKl6GWQW-KLnhtfw5n_84IRQ';

$token = '';
$payload = array();

if(isset($_GET['token']))
{
	$connect = new PDO("mysql:host=localhost; dbname=testing", "root", "password");
	$decoded = JWT::decode($_GET['token'], new Key($key, 'HS256'));
	$checkQuery = 'SELECT email_verification_status FROM user WHERE user_email = "'.$decoded->email.'"';
	$result = $connect->query($checkQuery);
	foreach($result as $row)
	{
		if($row['email_verification_status'] === 'Verified')
		{
			$payload = array(
				'msg'	=>	'Your Email Already Verified, You can login'
			);
		}
		else
		{
			$query = 'UPDATE user SET email_verification_status = "Verified" WHERE user_email = "'.$decoded->email.'"';
			$statement = $connect->prepare($query);
			$statement->execute();
			$payload = array(
				'msg'	=>	'Email Successfully verify, now you can login'
			);
		}
		$token = JWT::encode($payload, $key, 'HS256');
		header('location:index.php?token='.$token);
	}
}

?>


index.php

<?php

//index.php

require 'vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$key = '1a3LM3W966D6QTJ5BJb9opunkUcw_d09NCOIJb9QZTsrneqOICoMoeYUDcd_NfaQyR787PAH98Vhue5g938jdkiyIZyJICytKlbjNBtebaHljIR6-zf3A2h3uy6pCtUFl1UhXWnV6madujY4_3SyUViRwBUOP-UudUL4wnJnKYUGDKsiZePPzBGrF4_gxJMRwF9lIWyUCHSh-PRGfvT7s1mu4-5ByYlFvGDQraP4ZiG5bC1TAKO_CnPyd1hrpdzBzNW4SfjqGKmz7IvLAHmRD-2AMQHpTU-hN2vwoA-iQxwQhfnqjM0nnwtZ0urE6HjKl6GWQW-KLnhtfw5n_84IRQ';

$message = '';
$error = '';

if(isset($_GET['token']))
{
	$decoded = JWT::decode($_GET['token'], new Key($key, 'HS256'));
	$message = $decoded->msg;
}

if(isset($_POST["login"]))
{
	$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "password");

	if(empty($_POST["email"])){
		$error = 'Please Enter Email Details';
	} else if(empty($_POST["password"])){
		$error = 'Please Enter Password Details';
	} else {
		$query = "SELECT * FROM user WHERE user_email = ?";
		$statement = $connect->prepare($query);
		$statement->execute([$_POST["email"]]);
		$data = $statement->fetch(PDO::FETCH_ASSOC);
		if($data){
			if($data['user_password'] ===  $_POST['password']){
				
				$token = JWT::encode(
					array(
						'iat'		=>	time(),
						'nbf'		=>	time(),
						'exp'		=>	time() + 3600,
						'data'	=> array(
							'user_id'	=>	$data['user_id'],
							'user_name'	=>	$data['user_name']
						)
					),
					$key,
					'HS256'
				);
				setcookie("token", $token, time() + 3600, "/", "", true, true);
				header('location:welcome.php');

			} else {
				$error = 'Wrong Password';
			}
		} else {
			$error = 'Wrong Email Address';
		}
	}
}

?>


<!doctype html>
<html lang="en">
  	<head>
    	<!-- Required meta tags -->
    	<meta charset="utf-8">
    	<meta name="viewport" content="width=device-width, initial-scale=1">

    	<!-- Bootstrap CSS -->
    	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    	<title>How to Create Login using JWT Token in PHP</title>
  	</head>
  	<body>
    	<div class="container">
    		<h1 class="text-center mt-5 mb-5">How to Create Login using JWT Token in PHP</h1>
    		<div class="row">
    			<div class="col-md-4">&nbsp;</div>
    			<div class="col-md-4">
    				<?php

    				if($error !== '')
    				{
    					echo '<div class="alert alert-danger">'.$error.'</div>';
    				}

    				if($message !== '')
    				{
    					echo '<div class="alert alert-info">'.$message.'</div>';
    				}

    				?>
		    		<div class="card">
		    			<div class="card-header">Login</div>
		    			<div class="card-body">
		    				<form method="post">
		    					<div class="mb-3">
			    					<label>Email</label>
			    					<input type="email" name="email" class="form-control" />
			    				</div>
			    				<div class="mb-3">
			    					<label>Password</label>
			    					<input type="password" name="password" class="form-control" />
			    				</div>
			    				<div class="text-center">
			    					<input type="submit" name="login" class="btn btn-primary" value="Login" />
			    				</div>
		    				</form>
		    			</div>
		    		</div>
		    	</div>
	    	</div>
    	</div>
  	</body>
</html>


welcome.php

<?php

//welcome.php

require 'vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$key = '1a3LM3W966D6QTJ5BJb9opunkUcw_d09NCOIJb9QZTsrneqOICoMoeYUDcd_NfaQyR787PAH98Vhue5g938jdkiyIZyJICytKlbjNBtebaHljIR6-zf3A2h3uy6pCtUFl1UhXWnV6madujY4_3SyUViRwBUOP-UudUL4wnJnKYUGDKsiZePPzBGrF4_gxJMRwF9lIWyUCHSh-PRGfvT7s1mu4-5ByYlFvGDQraP4ZiG5bC1TAKO_CnPyd1hrpdzBzNW4SfjqGKmz7IvLAHmRD-2AMQHpTU-hN2vwoA-iQxwQhfnqjM0nnwtZ0urE6HjKl6GWQW-KLnhtfw5n_84IRQ';

if(isset($_COOKIE['token'])){
	$decoded = JWT::decode($_COOKIE['token'], new Key($key, 'HS256'));
} else {
	header('location:index.php');
}

?>

<!doctype html>
<html lang="en">
  	<head>
    	<!-- Required meta tags -->
    	<meta charset="utf-8">
    	<meta name="viewport" content="width=device-width, initial-scale=1">

    	<!-- Bootstrap CSS -->
    	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    	<title>How to Create Login in PHP using JWT Token</title>
  	</head>
  	<body>
    	<div class="container">
    		<h1 class="text-center mt-5 mb-5">How to Create Login in PHP using JWT Token</h1>
    		<div class="row">
    			<div class="col-md-4">&nbsp;</div>
    			<div class="col-md-4 text-center">
    				<h1>Welcome <b><?php echo $decoded->data->user_name; ?></b></h1>
    				<a href="logout.php">Logout</a>
    				
		    	</div>
	    	</div>
    	</div>
  	</body>
</html>


logout.php

<?php

//logout.php

setcookie("token", "", time() - 3600,  "/", "", true, true);

header('location:index.php');

?>


Thursday, 25 June 2020

PHP Login Registration with Email Verification using OTP



Normally after user registration, we have send email at user register email address for confirm his or her email address. Once User has click on email confirmation link then after that user registration process has been completed with email verification.

But in this post, we have use OTP (One Time Password) method for verify registered user email address. Email verification is a very required process for check registered user has enter right information at the time of registration and it is also useful to prevent spam registration at our web application. For this reason verify user identity, we have to verify his or her email address. In this OTP method, If User has provide us genuine email address then on that email address our system will send one email confirmation email with OTP number. User has to just copy that OTP number and enter in email verification page which will be load after submitting registration form data. In that web page, User has to enter OTP number and submit form. After submitting form user email address will be verified.
In most of the dynamic website, there is user registration form. By fill up user registration form, user can register into web page. So in that registration form, If you have use OTP code for user email address verification, then it is the secure method for verify user email address. In this method, OTP Code will be generated at once user has submitted registration form details, and that OTP code will be received at registered user email address. So, when user has enters the OTP code then PHP web application will verify user email address via that OTP code.

In this tutorial, we will learn User registration process with email verification by using OTP method and here we will send OTP code using email. By using this OTP Code method user email address will be validated once user has enter OTP number which he or she received at their email address. Below you can find the source code of PHP registration system with email verification process using OTP method. In source code you can find how registration form has been made, then after we have first validated user registration form data by using PHP function. After form data verification, we have write PHP script to enter only unique user email data into Mysql database and then after send email with OTP number to registered user email address for email confirmation. After this you can find the source code of email verification by using OTP method.




How to Implement OTP based Login in PHP




In this PHP Registration with email verification using OTP method tutorial, here we have add one more feature like Login using OTP. In this section you can get the solution of Login into system using OTP. We all know OTP means one time password and this OTP number will be generated randomly by using PHP function and that randomly generated OTP number will be stored in Mysql database. So when you have login into system then that OTP number will be expired.

Now we have describe you, how to Login using OTP works. So, when you have login into system, then first you have to enter your login credentials like email address and password details. Then If you have enter right login information then at backend it will generated OTP number and that OTP number will be send to your registered email address. So you have to go to your email address inbox and copy that OTP number and enter into system. Once you have enter valid OTP number then system will validate and you can login into system and that OTP number has been expired. So, in this tutorial, we will OTP based Login system in PHP and below you can find the source code of it.

Make Default Avatar In PHP After User Registration





In this PHP Login Registration tutorial, we have add one more feature like create register user dynamic initial avatar once user has complete their registration process. This type of initial avatar or profile image we can see, when we have create account in Google, then after login into Google account then we can see our name first character image in place of profile image. So when we have register into Google system then it has by default create our initial avatar by using our name first character. We can change that avatar or profile image later by uploading image. So, this type of creating initial avatar from register user name feature we have made in this Login Registration tutorial by using PHP script.


PHP Resend Email Verification Mail with OTP Number




In this PHP Login Registration system, we have add one more feature like How can we resend email with OTP number for email verification process. For some reason, If User have completed their registration process but user has not received verification email with OTP number. Then at that time how user can verify their email address and again they cannot register into system, this is because user email address has been inserted in our system. So for overcome this problem, we have add this resend email verification email with OTP number by using PHP script. In this feature, User has to enter his or her register email which is not verified yet, then User has to enter that email address and User can again received email verification email with OTP Number.

PHP Forgot Password Recover using OTP Code


In this section of PHP Login Registration tutorial, we will learn How to reset forgot password by using OTP Code with PHP script. In this feature, User must have to register in our system, so if that user has forgot their password. Then by using this feature they can easily recover their forgot password. For make this feature, we have use PHP scipt, mysql database and PHPMailer class for send password reset OTP number to register email address.

In this feature, first Users has to enter their email address in forgot password form. Here user has to enter only that email which is register in system. If User enter register email address, then they will received one email address in which they can get OTP number. After submit form details then new web page has been load and in that page User has to enter OTP number which is received at their email address. After entering OTP number then after again new form has been load on web page, and here User has to reset new password and submit form. After submitting form User password will be reset and they can again login into system. So, in this section we have make PHP forgot password script using OTP method.






Source Code


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `login_data`
--

CREATE TABLE `login_data` (
  `login_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `login_otp` int(6) NOT NULL,
  `last_activity` datetime NOT NULL,
  `login_datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `register_user`
--

CREATE TABLE `register_user` (
  `register_user_id` int(11) NOT NULL,
  `user_name` varchar(250) NOT NULL,
  `user_email` varchar(250) NOT NULL,
  `user_password` varchar(250) NOT NULL,
  `user_activation_code` varchar(250) NOT NULL,
  `user_email_status` enum('not verified','verified') NOT NULL,
  `user_otp` int(11) NOT NULL,
  `user_datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `user_avatar` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `login_data`
--
ALTER TABLE `login_data`
  ADD PRIMARY KEY (`login_id`);

--
-- Indexes for table `register_user`
--
ALTER TABLE `register_user`
  ADD PRIMARY KEY (`register_user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `login_data`
--
ALTER TABLE `login_data`
  MODIFY `login_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;

--
-- AUTO_INCREMENT for table `register_user`
--
ALTER TABLE `register_user`
  MODIFY `register_user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28;





index.php



<?php

//index.php

//error_reporting(E_ALL);

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

include('function.php');

$connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

$message = '';
$error_user_name = '';
$error_user_email = '';
$error_user_password = '';
$user_name = '';
$user_email = '';
$user_password = '';

if(isset($_POST["register"]))
{
 if(empty($_POST["user_name"]))
 {
  $error_user_name = "<label class='text-danger'>Enter Name</label>";
 }
 else
 {
  $user_name = trim($_POST["user_name"]);
  $user_name = htmlentities($user_name);
 }

 if(empty($_POST["user_email"]))
 {
  $error_user_email = '<label class="text-danger">Enter Email Address</label>';
 }
 else
 {
  $user_email = trim($_POST["user_email"]);
  if(!filter_var($user_email, FILTER_VALIDATE_EMAIL))
  {
   $error_user_email = '<label class="text-danger">Enter Valid Email Address</label>';
  }
 }

 if(empty($_POST["user_password"]))
 {
  $error_user_password = '<label class="text-danger">Enter Password</label>';
 }
 else
 {
  $user_password = trim($_POST["user_password"]);
  $user_password = password_hash($user_password, PASSWORD_DEFAULT);
 }

 if($error_user_name == '' && $error_user_email == '' && $error_user_password == '')
 {
  $user_activation_code = md5(rand());

  $user_otp = rand(100000, 999999);

  $data = array(
   ':user_name'  => $user_name,
   ':user_email'  => $user_email,
   ':user_password' => $user_password,
   ':user_activation_code' => $user_activation_code,
   ':user_email_status'=> 'not verified',
   ':user_otp'   => $user_otp
  );

  $query = "
  INSERT INTO register_user 
  (user_name, user_email, user_password, user_activation_code, user_email_status, user_otp)
  SELECT * FROM (SELECT :user_name, :user_email, :user_password, :user_activation_code, :user_email_status, :user_otp) AS tmp
  WHERE NOT EXISTS (
      SELECT user_email FROM register_user WHERE user_email = :user_email
  ) LIMIT 1
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($connect->lastInsertId() == 0)
  {
   $message = '<label class="text-danger">Email Already Register</label>';
  } 
  else
  {
   $user_avatar = make_avatar(strtoupper($user_name[0]));

   $query = "
   UPDATE register_user 
   SET user_avatar = '".$user_avatar."' 
   WHERE register_user_id = '".$connect->lastInsertId()."'
   ";

   $statement = $connect->prepare($query);

   $statement->execute();


   require 'class/class.phpmailer.php';
   $mail = new PHPMailer;
   $mail->IsSMTP();
   $mail->Host = 'smtpout.secureserver.net';
   $mail->Port = '80';
   $mail->SMTPAuth = true;
   $mail->Username = 'xxxxxxxxxxxxxx';
   $mail->Password = 'xxxxxxxxxxxxxx';
   $mail->SMTPSecure = '';
   $mail->From = 'tutorial@webslesson.info';
   $mail->FromName = 'Webslesson';
   $mail->AddAddress($user_email);
   $mail->WordWrap = 50;
   $mail->IsHTML(true);
   $mail->Subject = 'Verification code for Verify Your Email Address';

   $message_body = '
   <p>For verify your email address, enter this verification code when prompted: <b>'.$user_otp.'</b>.</p>
   <p>Sincerely,</p>
   <p>Webslesson.info</p>
   ';
   $mail->Body = $message_body;

   if($mail->Send())
   {
    echo '<script>alert("Please Check Your Email for Verification Code")</script>';

    header('location:email_verify.php?code='.$user_activation_code);
   }
   else
   {
    $message = $mail->ErrorInfo;
   }
  }

 }
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Registration with Email Verification using OTP</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">PHP Registration with Email Verification using OTP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Registration</h3>
    </div>
    <div class="panel-body">
     <?php echo $message; ?>
     <form method="post">
      <div class="form-group">
       <label>Enter Your Name</label>
       <input type="text" name="user_name" class="form-control" />
       <?php echo $error_user_name; ?>
      </div>
      <div class="form-group">
       <label>Enter Your Email</label>
       <input type="text" name="user_email" class="form-control" />
       <?php echo $error_user_email; ?>
      </div>
      <div class="form-group">
       <label>Enter Your Password</label>
       <input type="password" name="user_password" class="form-control" />
       <?php echo $error_user_password; ?>
      </div>
      <div class="form-group">
       <input type="submit" name="register" class="btn btn-success" value="Click to Register" />&nbsp;&nbsp;&nbsp;
       <a href="resend_email_otp.php" class="btn btn-default">Resend OTP</a>
       &nbsp;&nbsp;&nbsp;
       <a href="login.php">Login</a>
      </div>
     </form>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>


email_verify.php



<?php

//email_verify.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

$error_user_otp = '';
$user_activation_code = '';
$message = '';

if(isset($_GET["code"]))
{
 $user_activation_code = $_GET["code"];

 if(isset($_POST["submit"]))
 {
  if(empty($_POST["user_otp"]))
  {
   $error_user_otp = 'Enter OTP Number';
  }
  else
  {
   $query = "
   SELECT * FROM register_user 
   WHERE user_activation_code = '".$user_activation_code."' 
   AND user_otp = '".trim($_POST["user_otp"])."'
   ";

   $statement = $connect->prepare($query);

   $statement->execute();

   $total_row = $statement->rowCount();

   if($total_row > 0)
   {
    $query = "
    UPDATE register_user 
    SET user_email_status = 'verified' 
    WHERE user_activation_code = '".$user_activation_code."'
    ";

    $statement = $connect->prepare($query);

    if($statement->execute())
    {
     header('location:login.php?register=success');
    }
   }
   else
   {
    $message = '<label class="text-danger">Invalid OTP Number</label>';
   }
  }
 }
}
else
{
 $message = '<label class="text-danger">Invalid Url</label>';
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Registration with Email Verification using OTP</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">PHP Registration with Email Verification using OTP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Enter OTP Number</h3>
    </div>
    <div class="panel-body">
     <?php echo $message; ?>
     <form method="POST">
      <div class="form-group">
       <label>Enter OTP Number</label>
       <input type="text" name="user_otp" class="form-control" />
       <?php echo $error_user_otp; ?>
      </div>
      <div class="form-group">
       <input type="submit" name="submit" class="btn btn-success" value="Submit" />
      </div>
     </form>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>



login.php



<?php

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Login with OTP Authentication</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">How to Make Initial Avatar Image in PHP After Registration</h3>
   <br />

   <?php
   if(isset($_GET["register"]))
   {
    if($_GET["register"] == 'success')
    {
     echo '
     <h1 class="text-success">Email Successfully verified, Registration Process Completed...</h1>
     ';
    }
   }

   if(isset($_GET["reset_password"]))
   {
    if($_GET["reset_password"] == 'success')
    {
     echo '<h1 class="text-success">Password change Successfully, Now you can login with your new password</h1>';
    }
   }
   ?>

   <div class="row">
    <div class="col-md-3">&nbsp;</div>
    <div class="col-md-6">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">Login</h3>
      </div>
      <div class="panel-body">
       <form method="POST" id="login_form">
        <div class="form-group" id="email_area">
         <label>Enter Email Address</label>
         <input type="text" name="user_email" id="user_email" class="form-control" />
         <span id="user_email_error" class="text-danger"></span>
        </div>
        <div class="form-group" id="password_area" style="display:none;">
         <label>Enter password</label>
         <input type="password" name="user_password" id="user_password" class="form-control" />
         <span id="user_password_error" class="text-danger"></span>
        </div>
        <div class="form-group" id="otp_area" style="display:none;">
         <label>Enter OTP Number</label>
         <input type="text" name="user_otp" id="user_otp" class="form-control" />
         <span id="user_otp_error" class="text-danger"></span>
        </div>
        <div class="form-group" align="right">
         <input type="hidden" name="action" id="action" value="email" />
         <input type="submit" name="next" id="next" class="btn btn-primary" value="Next" />
        </div>
       </form>
      </div>
     </div>
     <div align="center">
      <b><a href="forget_password.php?step1=1">Forgot Password</a></b>
     </div>
    </div>
   </div>
   
  </div>
  <br />
  <br />
 </body>
</html>

<script>

$(document).ready(function(){
 $('#login_form').on('submit', function(event){
  event.preventDefault();
  var action = $('#action').val();
  $.ajax({
   url:"login_verify.php",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function()
   {
    $('#next').attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#next').attr('disabled', false);
    if(action == 'email')
    {
     if(data.error != '')
     {
      $('#user_email_error').text(data.error);
     }
     else
     {
      $('#user_email_error').text('');
      $('#email_area').css('display', 'none');
      $('#password_area').css('display', 'block');
     }
    }
    else if(action == 'password')
    {
     if(data.error != '')
     {
      $('#user_password_error').text(data.error);
     }
     else
     {
      $('#user_password_error').text('');
      $('#password_area').css('display', 'none');
      $('#otp_area').css('display', 'block');
     }
    }
    else
    {
     if(data.error != '')
     {
      $('#user_otp_error').text(data.error);
     }
     else
     {
      window.location.replace("home.php");
     }
    }

    $('#action').val(data.next_action);
   }
  })
 });
});

</script>








login_verify.php



<?php

//login_verify.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

session_start();

$error = '';

$next_action = '';

sleep(2);

if(isset($_POST["action"]))
{
 if($_POST["action"] == 'email')
 {
  if($_POST["user_email"] != '')
  {
   $data = array(
    ':user_email' => $_POST["user_email"]
   );

   $query = "
   SELECT * FROM register_user 
   WHERE user_email = :user_email
   ";

   $statement = $connect->prepare($query);

   $statement->execute($data);

   $total_row = $statement->rowCount();

   if($total_row == 0)
   {
    $error = 'Email Address not found';

    $next_action = 'email';
   }
   else
   {
    $result = $statement->fetchAll();

    foreach($result as $row)
    {
     $_SESSION["register_user_id"] = $row["register_user_id"];

     $_SESSION["user_name"] = $row["user_name"];

     $_SESSION['user_email'] = $row["user_email"];

     $_SESSION["user_password"] = $row["user_password"];
    }
    $next_action = 'password';
   }
  }
  else
  {
   $error = 'Email Address is Required';

   $next_action = 'email';
  }
 }

 if($_POST["action"] == 'password')
 {
  if($_POST["user_password"] != '')
  {
   if(password_verify($_POST["user_password"], $_SESSION["user_password"]))
   {
    $login_otp = rand(100000,999999);

    $data = array(
     ':user_id'  => $_SESSION["register_user_id"],
     ':login_otp' => $login_otp,
     ':last_activity'=> date('d-m-y h:i:s')
    );

    $query = "
    INSERT INTO login_data 
    (user_id, login_otp, last_activity) 
    VALUES (:user_id, :login_otp, :last_activity)
    ";

    $statement = $connect->prepare($query);

    if($statement->execute($data))
    {
     $_SESSION['login_id'] = $connect->lastInsertId();
     $_SESSION['login_otp'] = $login_otp;

     require 'class/class.phpmailer.php';

     $mail = new PHPMailer;

     $mail->IsSMTP();

     $mail->Host = 'smtpout.secureserver.net';

     $mail->Port = '80';

     $mail->SMTPAuth = true;

     $mail->Username = 'xxxxxxxxxxxxxx';
     $mail->Password = 'xxxxxxxxxxxxxx';

     $mail->SMTPSecure = '';

     $mail->From = 'tutorial@webslesson.info';

     $mail->FromName = 'Webslesson';

     $mail->AddAddress($_SESSION["user_email"]);

     $mail->WordWrap = 50;

     $mail->IsHTML(true);

     $mail->Subject = 'Verification code for Login';

     $message_body = '
     <p>For verify your login details, enter this verification code when prompted: <b>'.$login_otp.'</b>.</p>
     <p>Sincerely,</p>
     <p>Webslesson.info</p>
     ';

     $mail->Body = $message_body;

     if($mail->Send())
     {
      $next_action = 'otp';
     }
     else
     {
      $error = '<label class="text-danger">'.$mail->ErrorInfo.'</label>';
      $next_action = 'password';
     }
    }
   }
   else
   {
    $error = 'Wrong Password';
    $next_action = 'password';
   }
  }
  else
  {
   $error = 'Password is Required';
   $next_action = 'password';
  }
 }

 if($_POST["action"] == "otp")
 {
  if($_POST["user_otp"] != '')
  {
   if($_SESSION['login_otp'] == $_POST["user_otp"])
   {
    $_SESSION['user_id'] = $_SESSION['register_user_id'];
    unset($_SESSION["register_user_id"]);
    unset($_SESSION["user_email"]);
    unset($_SESSION["user_password"]);
    unset($_SESSION["login_otp"]);
   }
   else
   {
    $error = 'Wrong OTP Number';
    $next_action = 'otp';
   }
  }
  else
  {
   $error = 'OTP Number is required';
   $next_action = 'otp';
  }
 }





 $output = array(
  'error'   => $error,
  'next_action' => $next_action
 );

 echo json_encode($output);
}


?>


home.php



<?php

//home.php

session_start();

if(!isset($_SESSION["user_id"]))
{
 header("location:login.php");
}

include('database_connection.php');

include('function.php');

$user_name = '';
$user_id = '';

if(isset($_SESSION["user_name"], $_SESSION["user_id"]))
{
 $user_name = $_SESSION["user_name"];
 $user_id = $_SESSION["user_id"];
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Login with OTP Authentication</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">How to Make Initial Avatar Image in PHP After Registration</h3>
   <br />
   <br />
   <div class="row">
    <div class="col-md-9">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">User Timeline</h3>
      </div>
      <div class="panel-body">
       <h1 align="center">Welcome <?php echo $user_name; ?></h1>
      </div>
     </div>
    </div>
    <div class="col-md-3">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">User Details</h3>
      </div>
      <div class="panel-body">
       <div align="center">
        <?php
        Get_user_avatar($user_id, $connect);
        echo '<br /><br />';
        echo $user_name;
        ?>
        <br />
        <br />
        <a href="logout.php" class="btn btn-default">Logout</a>
       </div>
      </div>
     </div>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>


logout.php



<?php

//logout.php

session_start();

session_destroy();

header("location:login.php");

?>


resend_email_otp.php



<?php

//resend_email_otp.php

include('database_connection.php');

$message = '';

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

if(isset($_POST["resend"]))
{
 if(empty($_POST["user_email"]))
 {
  $message = '<div class="alert alert-danger">Email Address is required</div>';
 }
 else
 {
  $data = array(
   ':user_email' => trim($_POST["user_email"])
  );

  $query = "
  SELECT * FROM register_user 
  WHERE user_email = :user_email
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($statement->rowCount() > 0)
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    if($row["user_email_status"] == 'verified')
    {
     $message = '<div class="alert alert-info">Email Address already verified, you can login into system</div>';
    }
    else
    {
     require 'class/class.phpmailer.php';
     $mail = new PHPMailer;
     $mail->IsSMTP();
     $mail->Host = 'smtpout.secureserver.net';
     $mail->Port = '80';
     $mail->SMTPAuth = true;
     $mail->Username = 'xxxxxxxxx';
     $mail->Password = 'xxxxxxxxx';
     $mail->SMTPSecure = '';
     $mail->From = 'tutorial@webslesson.info';
     $mail->FromName = 'Webslesson';
     $mail->AddAddress($row["user_email"]);
     $mail->WordWrap = 50;
     $mail->IsHTML(true);
     $mail->Subject = 'Verification code for Verify Your Email Address';
     $message_body = '
     <p>For verify your email address, enter this verification code when prompted: <b>'.$row["user_otp"].'</b>.</p>
     <p>Sincerely,</p>
     ';
     $mail->Body = $message_body;

     if($mail->Send())
     {
      echo '<script>alert("Please Check Your Email for Verification Code")</script>';
      echo '<script>window.location.replace("email_verify.php?code='.$row["user_activation_code"].'");</script>';
     }
     else
     {

     }
    }
   }
  }
  else
  {
   $message = '<div class="alert alert-danger">Email Address not found in our record</div>';
  }
 }
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>Resend Email Verification OTP in PHP Registration</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Resend Email Verification OTP in PHP Registration</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Resend Email Verification OTP</h3>
    </div>
    <div class="panel-body">
     <?php echo $message; ?>
     <form method="post">
      <div class="form-group">
       <label>Enter Your Email</label>
       <input type="email" name="user_email" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="resend" class="btn btn-success" value="Send" />
      </div>
     </form>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>





forget_password.php



<?php

//forget_password.php

include('database_connection.php');

$message = '';

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

if(isset($_POST["submit"]))
{
 if(empty($_POST["user_email"]))
 {
  $message = '<div class="alert alert-danger">Email Address is required</div>';
 }
 else
 {
  $data = array(
   ':user_email' => trim($_POST["user_email"])
  );

  $query = "
  SELECT * FROM register_user 
  WHERE user_email = :user_email
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($statement->rowCount() > 0)
  {
   $result = $statement->fetchAll();

   foreach($result as $row)
   {
    if($row["user_email_status"] == 'not verified')
    {
     $message = '<div class="alert alert-info">Your Email Address is not verify, so first verify your email address by click on this <a href="resend_email_otp.php">link</a></div>';
    }
    else
    {
     $user_otp = rand(100000, 999999);

     $sub_query = "
     UPDATE register_user 
     SET user_otp = '".$user_otp."' 
     WHERE register_user_id = '".$row["register_user_id"]."'
     ";

     $connect->query($sub_query);

     require 'class/class.phpmailer.php';

     $mail = new PHPMailer;

     $mail->IsSMTP();

     $mail->Host = 'smtpout.secureserver.net';

     $mail->Port = '80';

     $mail->SMTPAuth = true;

     $mail->Username = 'xxxxxxxxxxxx';

     $mail->Password = 'xxxxxxxxxxx';

     $mail->SMTPSecure = '';

     $mail->From = 'tutorial@webslesson.info';

     $mail->FromName = 'Webslesson';

     $mail->AddAddress($row["user_email"]);

     $mail->IsHTML(true);

     $mail->Subject = 'Password reset request for your account';

     $message_body = '
     <p>For reset your password, you have to enter this verification code when prompted: <b>'.$user_otp.'</b>.</p>
     <p>Sincerely,</p>
     ';

     $mail->Body = $message_body;

     if($mail->Send())
     {
      echo '<script>alert("Please Check Your Email for password reset code")</script>';

      echo '<script>window.location.replace("forget_password.php?step2=1&code=' . $row["user_activation_code"] . '")</script>';
     }
    }
   }
  }
  else
  {
   $message = '<div class="alert alert-danger">Email Address not found in our record</div>';
  }
 }
}

if(isset($_POST["check_otp"]))
{
 if(empty($_POST["user_otp"]))
 {
  $message = '<div class="alert alert-danger">Enter OTP Number</div>';
 }
 else
 {
  $data = array(
   ':user_activation_code'  => $_POST["user_code"],
   ':user_otp'     => $_POST["user_otp"]
  );

  $query = "
  SELECT * FROM register_user 
  WHERE user_activation_code = :user_activation_code 
  AND user_otp = :user_otp
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($statement->rowCount() > 0)
  {
   echo '<script>window.location.replace("forget_password.php?step3=1&code=' . $_POST["user_code"] . '")</script>';
  }
  else
  {
   $message = '<div class="alert alert-danger">Wrong OTP Number</div>';
  }
 }
}

if(isset($_POST["change_password"]))
{
 $new_password = $_POST["user_password"];
 $confirm_password = $_POST["confirm_password"];

 if($new_password == $confirm_password)
 {
  $query = "
  UPDATE register_user 
  SET user_password = '".password_hash($new_password, PASSWORD_DEFAULT)."' 
  WHERE user_activation_code = '".$_POST["user_code"]."'
  ";

  $connect->query($query);

  echo '<script>window.location.replace("login.php?reset_password=success")</script>';
 }
 else
 {
  $message = '<div class="alert alert-danger">Confirm Password is not match</div>';
 }
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>Forgot Password script in PHP using OTP</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Forgot Password script in PHP using OTP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Forgot Password script in PHP using OTP</h3>
    </div>
    <div class="panel-body">
     <?php

     echo $message;

     if(isset($_GET["step1"]))
     {
     ?>
     <form method="post">
      <div class="form-group">
       <label>Enter Your Email</label>
       <input type="text" name="user_email" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="submit" class="btn btn-success" value="Send" />
      </div>
     </form>
     <?php
     }
     if(isset($_GET["step2"], $_GET["code"]))
     {
     ?>
     <form method="POST">
      <div class="form-group">
       <label>Enter OTP Number</label>
       <input type="text" name="user_otp" class="form-control" />
      </div>
      <div class="form-group">
       <input type="hidden" name="user_code" value="<?php echo $_GET["code"]; ?>" />
       <input type="submit" name="check_otp" class="btn btn-success" value="Send" />
      </div>
     </form>
     <?php
     }

     if(isset($_GET["step3"], $_GET["code"]))
     {
     ?>
     <form method="post">
      <div class="form-group">
       <label>Enter New Password</label>
       <input type="password" name="user_password" class="form-control" />
      </div>
      <div class="form-group">
       <label>Enter Confirm Password</label>
       <input type="password" name="confirm_password" class="form-control" />
      </div>
      <div class="form-group">
       <input type="hidden" name="user_code" value="<?php echo $_GET["code"]; ?>" />
       <input type="submit" name="change_password" class="btn btn-success" value="Change" />
      </div>
     </form>
     <?php 
     }
     ?>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>


function.php



<?php

//function.php

function make_avatar($character)
{
    $path = "avatar/". time() . ".png";
 $image = imagecreate(200, 200);
 $red = rand(0, 255);
 $green = rand(0, 255);
 $blue = rand(0, 255);
    imagecolorallocate($image, $red, $green, $blue);  
    $textcolor = imagecolorallocate($image, 255,255,255);  

    imagettftext($image, 100, 0, 55, 150, $textcolor, 'font/arial.ttf', $character);  
    //header("Content-type: image/png");  
    imagepng($image, $path);
    imagedestroy($image);
    return $path;
}

function Get_user_avatar($user_id, $connect)
{
 $query = "
 SELECT user_avatar FROM register_user 
    WHERE register_user_id = '".$user_id."'
 ";

 $statement = $connect->prepare($query);

 $statement->execute();

 $result = $statement->fetchAll();

 foreach($result as $row)
 {
  echo '<img src="'.$row["user_avatar"].'" width="75" class="img-thumbnail img-circle" />';
 }
}

?>





Wednesday, 24 April 2019

Login Registration System with Email Verification in Laravel 5.8



Do you know you can make complete login registration system in Laravel 5.8 with email verification in single artisan command run. If you not know then this post will help you to learn Laravel login authentication and register with step by step guide from scratch. Because Laravel 5.8 has default Login Registration authentication system, so you can make complete login register system in Laravel 5.8 in single run of artisan command run. Here we will discuss step by step process to build Login authentication and register system in Larave 5.8 application. You don't have write any line of code for make login and register system in Laravel 5.8 application. Last release of Laravel 5.8 introduce new features with improvements. So, by using that new features we will make login and register system by using one artisan command like php artisan make:auth. It will create default controllers file, views blade file and set routes for Login and register system.

In this login registration system here we will also covered email verification feature also. So, here we will learn how to verify email address after user has done registration in Laravel 5.8 application. For email verification here we will use new Laravel feature like MustEmailVerify contracts. When user will verify email and it will authenticate and redirect to Laravel user dashboard. If User register and he has not verify his email address then user will not access dashboard of Laravel 5.8 application. In Laravel 5.8 email verification process is very simple and easy to use. We can also modify default Laravel email template and we can create custom email template of email verification, forget password and password reset. If you have use Laravel default Login Registration system then it will reduce your most of time of development.



Install Laravel 5.8


First we want to install Laravel 5.8 fresh set up in out system. For this we have to open terminal and write below command.


composer create-project --prefer-dist laravel/laravel firstApp


Configure .env file


Once you have done install Laravel 5.8 application, in next step we want to configuare .env file for Mysql configuration and email sending configuration.


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=



MAIL_DRIVER=smtp
MAIL_HOST=smtpout.secureserver.net
MAIL_PORT=80
MAIL_USERNAME=xxxxx
MAIL_PASSWORD=xxxxx
MAIL_ENCRYPTION=null





Generate Laravel 5.8 Application Key


After .env configuration completed then we have to generate application. For this we have to go command prompt and write following command for genrate laravel application key.


php artisan key:generate


Laravel 5.8 Database Migration


For make Login Register system we have to make User table in Mysql database. Here we will make User table from this Laravel 5.8 application by migrating database. But before migrating database by using command. First we have to open app/providers/AppServiceProvider.php and add two line of code under boot method.


<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }
}

?>


After this we have to go to command prompt and write following command, it will automatic create tables in mysql database and it will also create migration file.


php artisan migrate


After migrating of database, User.php file will be make under app folder. So, we have to open that file and add MustVerifyEmail contracts under the constuctor method. It is for enable email verification.

app/User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable  = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

?>


Laravel 5.8 Authentication


Here we will use Laravel 5.8 default Login Register system by using Laravel 5.8 authentication. For this we have to write following command in command prompt. This command will create controllers, routes and views files for Laravel authentication and registration.


php artisan make:auth


Add Route


For Email Verification, we need to add route under routes/web.php file.


<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes(['verify' => true]); 

Route::get('/home', 'HomeController@index')->name('home');


Add middleware in Controller


After this we need to add middleware in Controller constuctor. For this we have to open app/Http/Controllers/HomeController.php file and add $this->middleware([‘auth’, ‘verified’]); this line under constructor.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'verified']);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }
}

?>


Run Laravel 5.8 application


For run Laravel 5.8 application, we have to go to command prompt and write following command. It will start Laravel 5.8 application and return base url of your Laravel 5.8 application.


php artisan serve


This is complete step by step process for build User Login Register System in Laravel 5.8 application by using default Laravel 5.8 authentication.

Tuesday, 30 October 2018

User Registration and Login System in Codeigniter 3

Part 1



Part 2



Part 3



Part 4



Part 5



Part 6



Part 7




User authentication is a required feature of any Web application. Based on user authentication user can access the system by providing their user authentication details. So, in this post we are login to learn Complete user registration and login system in Codeigniter framework. If you have use Codeigniter Framework to your web project, then in that project you want to add give rights to user to register into your system, after completed registration process, user can login into system by providing his login details which he has used in registration process. If login details are proper then user can access system. So here we will make complete user authentication system in Codeigniter in which user can registration into system and login into system features. Here you can learn this login and registration functionality in Codeigniter framework.

If you are start learning Codeigniter framework for web devlopment, then you must have to learn User Register and Login system which is most required feature of any web based application, so you have to must learn this system in Codeigniter, so you can make web based application in Codeigniter in which you can add this User register and Login system. Codeigniter framework has many build-in libraries and helper class which will very helpful to make user authentication system. In this post we will use Codeigniter database library, session library, form validation library, email library for sending verification email address link, encrypt library for convert simple password into hash formatted password. We will also use Codeigniter url helper, form helper for make this user register and login system in Codeigniter framework.

Here we will make user registration and login system using Session in Codeigniter framework. In this post you can find step by step process for make user registration and login system in Codeigniter with Session library with Mysql database. In this system you can find following features of User Registration and Login system using Codeigniter framework with Mysql database.


  • User Registration form to submit user details and Insert into Mysql Database
  • Send email verification email to registered email address for email verification
  • Convert user simple password to hash string for user authentication
  • Register and Login form data validation
  • Check email already registered or not at the time of user registration
  • User login form for access into system
  • Store user authentication details in Session
  • User logout from system



Database table creation


For store user information, we have to required table in mysql table, following script will make table in mysql database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `codeigniter_register`
--

CREATE TABLE `codeigniter_register` (
  `id` int(11) NOT NULL,
  `name` varchar(250) NOT NULL,
  `email` varchar(250) NOT NULL,
  `password` text NOT NULL,
  `verification_key` varchar(250) NOT NULL,
  `is_email_verified` enum('no','yes') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `codeigniter_register`
--
ALTER TABLE `codeigniter_register`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `codeigniter_register`
--
ALTER TABLE `codeigniter_register`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;


Autoload Libraries & Helper


In User Register and Login system in Codeigniter, we have to load some libraries and helper at the time of first code execution. For this we have to open application/cofig/autoload.php file and load following files and helper.

autoload.php

$autoload['libraries'] = array('session','database');
$autoload['helper'] = array('url','form');







Database Connection


After load of required library and helper, we want to make database connection, for this we have to open application/config/database.php file and write following database configuration.

database.php

<?php

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'testing',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

?>


Controllers (Register.php)


This controller is used for handles all register replated functionality.
_construct() - This function is used for load form validation and encrypt library, register model at the time of new object of this class has been created.
index() - This function will load register form in browser.
validation() - This function has received register form request, in this function first we have validate form data using Codeigniter form validation library. After success validation of form data, it will proceed for insert data into mysql table. After successfully insert of register form data, this function will generate dynamic email verification email with dynamic email verification link and send email to registered email address using Codeigniter email library.
verify_email() - This function is used for verify email address, this function received request for email verification from email verification link. Once email has been verified user can login into system.


<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Register extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  if($this->session->userdata('id'))
  {
   redirect('private_area');
  }
  $this->load->library('form_validation');
  $this->load->library('encrypt');
  $this->load->model('register_model');
 }

 function index()
 {
  $this->load->view('register');
 }

 function validation()
 {
  $this->form_validation->set_rules('user_name', 'Name', 'required|trim');
  $this->form_validation->set_rules('user_email', 'Email Address', 'required|trim|valid_email|is_unique[codeigniter_register.email]');
  $this->form_validation->set_rules('user_password', 'Password', 'required');
  if($this->form_validation->run())
  {
   $verification_key = md5(rand());
   $encrypted_password = $this->encrypt->encode($this->input->post('user_password'));
   $data = array(
    'name'  => $this->input->post('user_name'),
    'email'  => $this->input->post('user_email'),
    'password' => $encrypted_password,
    'verification_key' => $verification_key
   );
   $id = $this->register_model->insert($data);
   if($id > 0)
   {
    $subject = "Please verify email for login";
    $message = "
    <p>Hi ".$this->input->post('user_name')."</p>
    <p>This is email verification mail from Codeigniter Login Register system. For complete registration process and login into system. First you want to verify you email by click this <a href='".base_url()."register/verify_email/".$verification_key."'>link</a>.</p>
    <p>Once you click this link your email will be verified and you can login into system.</p>
    <p>Thanks,</p>
    ";
    $config = array(
     'protocol'  => 'smtp',
     'smtp_host' => 'smtpout.secureserver.net',
     'smtp_port' => 80,
     'smtp_user'  => 'xxxxxxx', 
                  'smtp_pass'  => 'xxxxxxx', 
     'mailtype'  => 'html',
     'charset'    => 'iso-8859-1',
                   'wordwrap'   => TRUE
    );
    $this->load->library('email', $config);
    $this->email->set_newline("\r\n");
    $this->email->from('info@webslesson.info');
    $this->email->to($this->input->post('user_email'));
    $this->email->subject($subject);
    $this->email->message($message);
    if($this->email->send())
    {
     $this->session->set_flashdata('message', 'Check in your email for email verification mail');
     redirect('register');
    }
   }
  }
  else
  {
   $this->index();
  }
 }

 function verify_email()
 {
  if($this->uri->segment(3))
  {
   $verification_key = $this->uri->segment(3);
   if($this->register_model->verify_email($verification_key))
   {
    $data['message'] = '<h1 align="center">Your Email has been successfully verified, now you can login from <a href="'.base_url().'login">here</a></h1>';
   }
   else
   {
    $data['message'] = '<h1 align="center">Invalid Link</h1>';
   }
   $this->load->view('email_verification', $data);
  }
 }

}

?>


Controllers(Login.php)


In this Login controller you can find following function for all Login operation like, load login form, login form data verification.

_construct() - This function is used for load form validation and encrypt library, login model at the time of new object of this class has been created.
index() - This function will load Login form on web page.
validation() - This function received request for validate login details. After successfully verify user login details, page will redirect to private_area controller.


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  if($this->session->userdata('id'))
  {
   redirect('private_area');
  }
  $this->load->library('form_validation');
  $this->load->library('encrypt');
  $this->load->model('login_model');
 }

 function index()
 {
  $this->load->view('login');
 }

 function validation()
 {
  $this->form_validation->set_rules('user_email', 'Email Address', 'required|trim|valid_email');
  $this->form_validation->set_rules('user_password', 'Password', 'required');
  if($this->form_validation->run())
  {
   $result = $this->login_model->can_login($this->input->post('user_email'), $this->input->post('user_password'));
   if($result == '')
   {
    redirect('private_area');
   }
   else
   {
    $this->session->set_flashdata('message',$result);
    redirect('login');
   }
  }
  else
  {
   $this->index();
  }
 }

}

?>


Controller(Private_area.php)


After successfully validate login details page has been redirect to this controller. In this there following function.
_construct() - This function is used validate used login or not into system, if user not login into system then this function will redirect page to login form.
index() - This function will display Welcome user message with Logout page link.
logout() - This function will remove all session value, this function will logout user from system and redirect to login form.


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Private_area extends CI_Controller {
 public function __construct()
 {
  parent::__construct();
  if(!$this->session->userdata('id'))
  {
   redirect('login');
  }
 }

 function index()
 {
  echo '<br /><br /><br /><h1 align="center">Welcome User</h1>';
  echo '<p align="center"><a href="'.base_url().'private_area/logout">Logout</a></p>';
 }

 function logout()
 {
  $data = $this->session->all_userdata();
  foreach($data as $row => $rows_value)
  {
   $this->session->unset_userdata($row);
  }
  redirect('login');
 }
}

?>


Models(Register_model.php)


insert() - Models function is used for database operation, So this function will insert data into Mysql table.
verify_email($key) - This model function has been used for database operation for verify email address.


<?php
class Register_model extends CI_Model
{
 function insert($data)
 {
  $this->db->insert('codeigniter_register', $data);
  return $this->db->insert_id();
 }

 function verify_email($key)
 {
  $this->db->where('verification_key', $key);
  $this->db->where('is_email_verified', 'no');
  $query = $this->db->get('codeigniter_register');
  if($query->num_rows() > 0)
  {
   $data = array(
    'is_email_verified'  => 'yes'
   );
   $this->db->where('verification_key', $key);
   $this->db->update('codeigniter_register', $data);
   return true;
  }
  else
  {
   return false;
  }
 }
}

?>


Models(Login_model.php)


In this model there is only one function can_login($email, $password), this function is used to verify login form details with Mysql table details, If login details match then it will return true, otherwise it will return error message. This function convert hash password to simple string and match with Login form password.


<?php
class Login_model extends CI_Model
{
 function can_login($email, $password)
 {
  $this->db->where('email', $email);
  $query = $this->db->get('codeigniter_register');
  if($query->num_rows() > 0)
  {
   foreach($query->result() as $row)
   {
    if($row->is_email_verified == 'yes')
    {
     $store_password = $this->encrypt->decode($row->password);
     if($password == $store_password)
     {
      $this->session->set_userdata('id', $row->id);
     }
     else
     {
      return 'Wrong Password';
     }
    }
    else
    {
     return 'First verified your email address';
    }
   }
  }
  else
  {
   return 'Wrong Email Address';
  }
 }
}

?>


Views(register.php)


This html output file, which output we view on web page in browser. It will load register form on web page. In this file we have make register form, in which we have use set_value() form helper function, by using this function it can remember form data on form again load on validation error. Same way we have also use form_error() form validation library function for display form validation error on web page. Below you can find complete source code of registration form.


<!DOCTYPE html>
<html>
<head>
 <title>Complete User Registration and Login System in Codeigniter</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>

<body>
 <div class="container">
  <br />
  <h3 align="center">Complete User Registration and Login System in Codeigniter</h3>
  <br />
  <div class="panel panel-default">
   <div class="panel-heading">Register</div>
   <div class="panel-body">
    <form method="post" action="<?php echo base_url(); ?>register/validation">
     <div class="form-group">
      <label>Enter Your Name</label>
      <input type="text" name="user_name" class="form-control" value="<?php echo set_value('user_name'); ?>" />
      <span class="text-danger"><?php echo form_error('user_name'); ?></span>
     </div>
     <div class="form-group">
      <label>Enter Your Valid Email Address</label>
      <input type="text" name="user_email" class="form-control" value="<?php echo set_value('user_email'); ?>" />
      <span class="text-danger"><?php echo form_error('user_email'); ?></span>
     </div>
     <div class="form-group">
      <label>Enter Password</label>
      <input type="password" name="user_password" class="form-control" value="<?php echo set_value('user_password'); ?>" />
      <span class="text-danger"><?php echo form_error('user_password'); ?></span>
     </div>
     <div class="form-group">
      <input type="submit" name="register" value="Register" class="btn btn-info" />
     </div>
    </form>
   </div>
  </div>
 </div>
</body>
</html>


Views(email_verification.php)


This view file is used for display success message of email verification with Login link.


<!DOCTYPE html>
<html>
<head>
 <title>Complete Login Register system in Codeigniter</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>

<body>
 <div class="container">
  <br />
  <h3 align="center">Complete Login Register system in Codeigniter</h3>
  <br />
  
  <?php

  echo $message;
  
  ?>
  
 </div>
</body>
</html>


Views(login.php)


This view file will load Login form on web page.


<!DOCTYPE html>
<html>
<head>
    <title>Complete User Registration and Login System in Codeigniter</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>

<body>
    <div class="container">
        <br />
        <h3 align="center">Complete User Registration and Login System in Codeigniter</h3>
        <br />
        <div class="panel panel-default">
            <div class="panel-heading">Login</div>
            <div class="panel-body">
                <?php
                if($this->session->flashdata('message'))
                {
                    echo '
                    <div class="alert alert-success">
                        '.$this->session->flashdata("message").'
                    </div>
                    ';
                }
                ?>
                <form method="post" action="<?php echo base_url(); ?>login/validation">
                    <div class="form-group">
                        <label>Enter Email Address</label>
                        <input type="text" name="user_email" class="form-control" value="<?php echo set_value('user_email'); ?>" />
                        <span class="text-danger"><?php echo form_error('user_email'); ?></span>
                    </div>
                    <div class="form-group">
                        <label>Enter Password</label>
                        <input type="password" name="user_password" class="form-control" value="<?php echo set_value('user_password'); ?>" />
                        <span class="text-danger"><?php echo form_error('user_password'); ?></span>
                    </div>
                    <div class="form-group">
                        <input type="submit" name="login" value="Login" class="btn btn-info" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="<?php echo base_url(); ?>register">Register</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

So, this is complete source code of Codeigniter Login Register system, if you have any question regarding this tutorial, you can comment into comment box.

Monday, 4 December 2017

PHP Registration Script with Email Confirmation

In this post, We have start learning how can we send user activation email after completing user registration. Because if you have created an account on any website and have you verify you email by click through a verification link send by website for activate or verify email which you have enter email at the time of registration. So we have make this post to learn how can you build an email verification script step by step.

This is email verify PHP script in which you allows you to verify your email address at the time of registration. This email verification script used at the time of new registration or this script also required when in your site has rss subscription, then use has enter email for subscribe rss feed. So email must be original and reduce spam. So At that time we want to verify email address by sending verification link to that email address.

Here we have use simple PHP registration example to verify email address by sending email activation link to their account and by clicking on that link email will be verified. For make this script we have use PHP PDO script with Mysql Database and for sending email we have use PHPMailer Library. In this script user can register into site by entering proper email and after register with email address, then they will received email verification link into their email address. So if email will be proper then he will received email verification link. If user not verified their email address then he cannot login into site. For access website user want to verify their email address. This script helpful to reduce spam registration into website. For email verification user has go to email account and in his email address he will received email verification link with password. So user can verify email by clicking on that link. After email verification user can also received password in his email also. After this email verification user can login into system. This way we can verify email address for reduce span registration by using PHP PDO with Mysql Database and PHPMailer Library.








Source Code


database_connection.php



<?php
//database_connection.php

$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
session_start();

?>


register.php



<?php
//register.php

include('database_connection.php');

if(isset($_SESSION['user_id']))
{
 header("location:index.php");
}

$message = '';

if(isset($_POST["register"]))
{
 $query = "
 SELECT * FROM register_user 
 WHERE user_email = :user_email
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':user_email' => $_POST['user_email']
  )
 );
 $no_of_row = $statement->rowCount();
 if($no_of_row > 0)
 {
  $message = '<label class="text-danger">Email Already Exits</label>';
 }
 else
 {
  $user_password = rand(100000,999999);
  $user_encrypted_password = password_hash($user_password, PASSWORD_DEFAULT);
  $user_activation_code = md5(rand());
  $insert_query = "
  INSERT INTO register_user 
  (user_name, user_email, user_password, user_activation_code, user_email_status) 
  VALUES (:user_name, :user_email, :user_password, :user_activation_code, :user_email_status)
  ";
  $statement = $connect->prepare($insert_query);
  $statement->execute(
   array(
    ':user_name'   => $_POST['user_name'],
    ':user_email'   => $_POST['user_email'],
    ':user_password'  => $user_encrypted_password,
    ':user_activation_code' => $user_activation_code,
    ':user_email_status' => 'not verified'
   )
  );
  $result = $statement->fetchAll();
  if(isset($result))
  {
   $base_url = "http://localhost/tutorial/email-address-verification-script-using-php/";
   $mail_body = "
   <p>Hi ".$_POST['user_name'].",</p>
   <p>Thanks for Registration. Your password is ".$user_password.", This password will work only after your email verification.</p>
   <p>Please Open this link to verified your email address - ".$base_url."email_verification.php?activation_code=".$user_activation_code."
   <p>Best Regards,<br />Webslesson</p>
   ";
   require 'class/class.phpmailer.php';
   $mail = new PHPMailer;
   $mail->IsSMTP();        //Sets Mailer to send message using SMTP
   $mail->Host = 'smtpout.secureserver.net';  //Sets the SMTP hosts of your Email hosting, this for Godaddy
   $mail->Port = '80';        //Sets the default SMTP server port
   $mail->SMTPAuth = true;       //Sets SMTP authentication. Utilizes the Username and Password variables
   $mail->Username = 'xxxxxxxx';     //Sets SMTP username
   $mail->Password = 'xxxxxxxx';     //Sets SMTP password
   $mail->SMTPSecure = '';       //Sets connection prefix. Options are "", "ssl" or "tls"
   $mail->From = 'info@webslesson.info';   //Sets the From email address for the message
   $mail->FromName = 'Webslesson';     //Sets the From name of the message
   $mail->AddAddress($_POST['user_email'], $_POST['user_name']);  //Adds a "To" address   
   $mail->WordWrap = 50;       //Sets word wrapping on the body of the message to a given number of characters
   $mail->IsHTML(true);       //Sets message type to HTML    
   $mail->Subject = 'Email Verification';   //Sets the Subject of the message
   $mail->Body = $mail_body;       //An HTML or plain text message body
   if($mail->Send())        //Send an Email. Return true on success or false on error
   {
    $message = '<label class="text-success">Register Done, Please check your mail.</label>';
   }
  }
 }
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Register Login Script with Email Verification</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container" style="width:100%; max-width:600px">
   <h2 align="center">PHP Register Login Script with Email Verification</h2>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading"><h4>Register</h4></div>
    <div class="panel-body">
     <form method="post" id="register_form">
      <?php echo $message; ?>
      <div class="form-group">
       <label>User Name</label>
       <input type="text" name="user_name" class="form-control" pattern="[a-zA-Z ]+" required />
      </div>
      <div class="form-group">
       <label>User Email</label>
       <input type="email" name="user_email" class="form-control" required />
      </div>
      <div class="form-group">
       <input type="submit" name="register" id="register" value="Register" class="btn btn-info" />
      </div>
     </form>
     <p align="right"><a href="login.php">Login</a></p>
    </div>
   </div>
  </div>
 </body>
</html>


email_verification.php



<?php

include('database_connection.php');

$message = '';

if(isset($_GET['activation_code']))
{
 $query = "
  SELECT * FROM register_user 
  WHERE user_activation_code = :user_activation_code
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':user_activation_code'   => $_GET['activation_code']
  )
 );
 $no_of_row = $statement->rowCount();
 
 if($no_of_row > 0)
 {
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   if($row['user_email_status'] == 'not verified')
   {
    $update_query = "
    UPDATE register_user 
    SET user_email_status = 'verified' 
    WHERE register_user_id = '".$row['register_user_id']."'
    ";
    $statement = $connect->prepare($update_query);
    $statement->execute();
    $sub_result = $statement->fetchAll();
    if(isset($sub_result))
    {
     $message = '<label class="text-success">Your Email Address Successfully Verified <br />You can login here - <a href="login.php">Login</a></label>';
    }
   }
   else
   {
    $message = '<label class="text-info">Your Email Address Already Verified</label>';
   }
  }
 }
 else
 {
  $message = '<label class="text-danger">Invalid Link</label>';
 }
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Register Login Script with Email Verification</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  
  <div class="container">
   <h1 align="center">PHP Register Login Script with Email Verification</h1>
  
   <h3><?php echo $message; ?></h3>
   
  </div>
 
 </body>
 
</html>


login.php



<?php
//login.php

include('database_connection.php');

if(isset($_SESSION['user_id']))
{
 header("location:index.php");
}

$message = '';

if(isset($_POST["login"]))
{
 $query = "
 SELECT * FROM register_user 
  WHERE user_email = :user_email
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
    'user_email' => $_POST["user_email"]
  )
 );
 $count = $statement->rowCount();
 if($count > 0)
 {
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   if($row['user_email_status'] == 'verified')
   {
    if(password_verify($_POST["user_password"], $row["user_password"]))
    {
     $_SESSION['user_id'] = $row['register_user_id'];
     header("location:index.php");
    }
    else
    {
     $message = "<label>Wrong Password</label>";
    }
   }
   else
   {
    $message = "<label class='text-danger'>Please First Verify, your email address</label>";
   }
  }
 }
 else
 {
  $message = "<label class='text-danger'>Wrong Email Address</label>";
 }
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Register Login Script with Email Verification</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container" style="width:100%; max-width:600px">
   <h2 align="center">PHP Register Login Script with Email Verification</h2>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading"><h4>Login</h4></div>
    <div class="panel-body">
     <form method="post">
      <?php echo $message; ?>
      <div class="form-group">
       <label>User Email</label>
       <input type="email" name="user_email" class="form-control" required />
      </div>
      <div class="form-group">
       <label>Password</label>
       <input type="password" name="user_password" class="form-control" required />
      </div>
      <div class="form-group">
       <input type="submit" name="login" value="Login" class="btn btn-info" />
      </div>
     </form>
     <p align="right"><a href="register.php">Register</a></p>
    </div>
   </div>
  </div>
 </body>
</html>


logout.php



<?php
//logout.php
session_start();

session_destroy();

header("location:login.php");

?>


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `register_user`
--

CREATE TABLE IF NOT EXISTS `register_user` (
  `register_user_id` int(11) NOT NULL,
  `user_name` varchar(250) NOT NULL,
  `user_email` varchar(250) NOT NULL,
  `user_password` varchar(250) NOT NULL,
  `user_activation_code` varchar(250) NOT NULL,
  `user_email_status` enum('not verified','verified') NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `register_user`
--

INSERT INTO `register_user` (`register_user_id`, `user_name`, `user_email`, `user_password`, `user_activation_code`, `user_email_status`) VALUES
(1, 'John Smith', 'web-tutorial@programmer.net', '$2y$10$vdMwAmoRJfep8Vl4BI0QDOXArOCTOMbFs6Ja15qq3NEkPUBBtffD2', 'c74c4bf0dad9cbae3d80faa054b7d8ca', 'verified');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `register_user`
--
ALTER TABLE `register_user`
  ADD PRIMARY KEY (`register_user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `register_user`
--
ALTER TABLE `register_user`
  MODIFY `register_user_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;