Showing posts with label send activation email php. Show all posts
Showing posts with label send activation email php. 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');

?>


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;