Skip to main content
registered user's email verification script

PHP – Email Verification Script for Registered User


Toturial on PHP email verification script


Hello friends, today i am going to share with you tutorial about email verification script in PHP. Many time whenever you register on web-application. They will ask to you for verify your email. They will send you link on your email address and you have to click on it. Then you will redirect to their website and you will be verified user for that site. Today you will learn about the same process using PHP. Here we will perform this tutorial using bootstrap framework for create a registration form and other HTML-CSS work.

In this tutorial we will use this files.

  • index.php
  • submit.php
  • user_activation.php

In this tutorial, we will send email using Swiftmailer. Swiftmailer is mailer library for PHP. You can also use PHP Mailer for sending mail using PHP. You can check this tutorial Send email from localhost XAMPP using PHP. This is using swiftmailer.

Let’s start email verification in PHP step by step

First of all, we will create a html user registration form. In which, we have only three input fields i.e. email, password and confirm password. This user registration form is secure from client side (using jquery) as well as from server side. We have used bootstrap css framework for this form. So this is my code for registration form.

index.php

<!DOCTYPE html>
<html>
<head>
	<title>PHP email verification script</title>
	<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
	<link rel="stylesheet" type="text/css" href="css/custom.css">

	<!-- Script for Bootstrap JS -->
	<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
	<script type="text/javascript" src="js/bootstrap.min.js"></script>
</head>
<body>
<?php 
session_start();

$error = [
"email_error" => '',
"password_error" => '',
"confirm_pass_error" => ''
];

$form_data = [
"email" => '',
"password" => '',
"confirm_pass" => ''
];

if(!empty($_SESSION['error']))
{
	$error = $_SESSION['error'];
}

if(!empty($_SESSION['form_data']))
{
	$form_data = $_SESSION['form_data'];
}

?>
	<div class="container">
		<div class="form-section">
			<div class="row">
				<div class="col-md-6 col-md-offset-3">
					<h2>Sign Up here</h2>
				</div>
				<p class="master_error"></p>
			</div>
			<br>
			<div class="row">
				<div class="col-md-6 col-md-offset-3">
					<form action="submit.php" method="POST" role="form" onsubmit = "return validate();">
						<!-- <legend>Form title</legend> -->
					
						<div class="form-group">
							<label for="">E-mail</label>
							<input type="email" class="form-control" id="email" name="email" placeholder="Your email address" value="<?php echo $form_data['email']; ?>">
							<p class="email_error error"><?php echo $error['email_error']; ?></p>
						</div>

						<div class="form-group">
							<label for="">Password</label>
							<input type="password" class="form-control" id="password" name="password" placeholder="Choose your password" value="<?php echo $form_data['password']; ?>">
							<p class="password_error error"><?php echo $error['password_error']; ?></p>
						</div>

						<div class="form-group">
							<label for="">Confirm Password</label>
							<input type="password" class="form-control" id="confirm_pass" name="confirm_pass" placeholder="Retype your password" value="<?php echo $form_data['confirm_pass']; ?>">
							<p class="confirm_pass_error error"><?php echo $error['confirm_pass_error']; ?></p>
						</div>
			
						<button type="submit" class="btn btn-primary">Sign Up</button>

					</form>
				</div>
			</div>
		</div>
	</div>
</body>

<!-- Script for add new textbox -->
<script type="text/javascript">
function validate()
{
	return true;
	var valid = true;
	var email = $('#email').val();
	var password = $('#password').val();
	var confirm_pass = $('#confirm_pass').val();

	if(email == '')
	{
		valid = false;
		$('.email_error').html('* Email is required.');
	}
	else
	{
		$('.email_error').html('');	
	}

	if(password == '')
	{
		valid = false;
		$('.password_error').html('* Password is required.');
	}
	else
	{
		$('.password_error').html('');	
	}

	if(confirm_pass == '' )
	{
		valid = false;
		$('.confirm_pass_error').html('* Confirm password is required.');
	}
	else
	{
		$('.confirm_pass_error').html('');	
	}

	if(confirm_pass != '' && password != '')
	{
		if(password != confirm_pass)
		{
			valid = false;
			$('.confirm_pass_error').html('* Confirm password must be same as password.');
		}
		else
		{
			$('.confirm_pass_error').html('');	
		}
	}

	if(valid == true)
	{
		return true;
	}
	else
	{
		return false;
	}

}
</script>

</html>

<?php 
$_SESSION['error'] = "";
$_SESSION['form_data'] = "";
?>

Now i have a MySQL database named “test” and table name is “user“. In this table registered user’s information will store. This table has five fields user_id, user_email, user_password, is_active and activation_key. Here is_active field contain two values 0 and 1. 0 stand for inactive user and 1 stand for active user. By default is_active contain 0. When we send email verification email to that user and user click on the link at that time this is_active become 1 and his email will verify successfully. Then will prevent from spam email users. This is a logic behind this tutorial. So let’s see the code.

config.php

<?php
$db_hostname = 'localhost';         // Database hostname
$db_username = 'root';				// Database username
$db_password = '';					// Database password
$db_name = 'test';					// Database name

$conn = mysqli_connect($db_hostname, $db_username, $db_password, $db_name);

if(!$conn) 
{
	echo "Unable to connect database".mysqli_error($conn);die;
}
else
{
	// echo "Database connected successfully";
}
?>

submit.php

<?php 
session_start();
$valid = true;
$error = [];
$form_data = [];

if(!empty($_POST['email']))
{
	$email = $_POST['email'];
	$email_data = array("email" => $email);
	$form_data = array_merge($form_data, $email_data);
	$email_error = array("email_error" => "");
	$error = array_merge($error, $email_error);
	if (!filter_var($email, FILTER_VALIDATE_EMAIL)) 
	{
  		$email_error = array("email_error" => "* Valid emial format is 'abc@xxxx.com'.");
		$error = array_merge($error, $email_error);
	}
}
else
{
	$valid = false;
	$email = "";
	$email_data = array("email" => $email);
	$form_data = array_merge($form_data, $email_data);
	$email_error = array("email_error" => "* Email is required.");
	$error = array_merge($error, $email_error);
}

if(!empty($_POST['password']))
{
	$password = $_POST['password'];
	$password_data = array("password" => $password);
	$form_data = array_merge($form_data, $password_data);
	$password_error = array("password_error" => "");
	$error = array_merge($error, $password_error);
}
else
{
	$valid = false;
	$password = "";
	$password_data = array("password" => $password);
	$form_data = array_merge($form_data, $password_data);
	$password_error = array("password_error" => "* Password is required.");
	$error = array_merge($error, $password_error);
}

if(!empty($_POST['confirm_pass']))
{
	$confirm_pass = $_POST['confirm_pass'];
	$confirm_pass_data = array("confirm_pass" => $confirm_pass);
	$form_data = array_merge($form_data, $confirm_pass_data);
	$confirm_pass_error = array("confirm_pass_error" => "");
	$error = array_merge($error, $confirm_pass_error);
}
else
{
	$valid = false;
	$confirm_pass = "";
	$confirm_pass_data = array("confirm_pass" => $confirm_pass);
	$form_data = array_merge($form_data, $confirm_pass_data);
	$confirm_pass_error = array("confirm_pass_error" => "* Confirm password is required.");
	$error = array_merge($error, $confirm_pass_error);
}

if(!empty($password) && !empty($confirm_pass))
{
	if($password != $confirm_pass)
	{
		$valid = false;
		$confirm_pass = "";
		$confirm_pass_data = array("confirm_pass" => $confirm_pass);
		$form_data = array_merge($form_data, $confirm_pass_data);
		$confirm_pass_error = array("confirm_pass_error" => "* Confirm password must be same as password field.");
		$error = array_merge($error, $confirm_pass_error);
	}
	else
	{
		$valid = true;
		$confirm_pass = "";
		$confirm_pass_data = array("confirm_pass" => $confirm_pass);
		$form_data = array_merge($form_data, $confirm_pass_data);
		$confirm_pass_error = array("confirm_pass_error" => "");
		$error = array_merge($error, $confirm_pass_error);
	}
}

if($valid == true)
{
	include 'config.php';
	mysqli_select_db($conn,$db_name);
	$password = md5($password);
	$user_activation_key = md5(rand().time());
	$message = "Please active your account using this link <a href='http://127.0.0.1/project/email-varification-script/user_activation.php?key=".$user_activation_key."'>http://127.0.0.1/project/email-varification-script/user_activation.php?key=".$user_activation_key."</a>";
	$sql = "INSERT INTO user (user_id,user_email,user_password,is_active,activation_key) VALUES (NULL,'$email','$password','0','$user_activation_key')";
	$query = mysqli_query($conn,$sql);
	if($query)
	{
		require_once 'swiftmailer/lib/swift_required.php';

		// Create the Transport the call setUsername() and setPassword()
		$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
	  	->setUsername('your-email@gmail.com')
	  	->setPassword('your-password')
	  	;

	  	$mailer = Swift_Mailer::newInstance($transport);
		// Create the message
		$message = Swift_Message::newInstance()
		// Give the message a subject
		->setSubject('Verify your email address')
		// Set the From address with an associative array
		->setFrom(array('your-email@your-mail.com' => 'Your Name'))
		// Set the To addresses with an associative array
		->setTo(array($email))
		// Give it a body
		->setBody('Body Message')
		// And optionally an alternative body
		->addPart($message, 'text/html');
		// Optionally add any attachments
		$result = $mailer->send($message);

		if(!$result)
		{
			echo "Mail successfully not sent.";
		}
		else
		{
			echo "Mail sent successfully.";
		}		
	}
	else
	{

	}
}
else
{
	echo "<pre>";
	print_r($error);
	$_SESSION['error'] = $error;
	$_SESSION['form_data'] = $form_data;
	header('Location:index.php');
}
?>

When user click on submit button after filling information, information will send to submit.php file. In the submit.php file, user’s information will validate using PHP. Then this information will store in the database and send verification mail to that user for email verification.

When user click on the verification link which is in the verification email, “user_activation.php” file executed. This file update the status of user from INACTIVE to ACTIVE.

user_activation.php

<?php 
if(!empty($_GET['key']))
{
	$key = $_GET['key'];
}
else
{
	$key = '';
}

if($key != '')
{
	include 'config.php';
	mysqli_select_db($conn,$db_name);
	$sql = "SELECT * FROM user WHERE activation_key = '$key'";
	$query = mysqli_query($conn,$sql);
	$rows = mysqli_num_rows($query);
	if($rows == 1)
	{
		while($data = mysqli_fetch_array($query))
		{
			$is_active = $data['is_active'];
			if($is_active == 0)
			{
				$update_sql = "UPDATE user SET is_active='1' WHERE activation_key = '$key' ";
				$update_query = mysqli_query($conn,$update_sql);
				if(!$update_query)
				{
					echo "Error occured.";
				}
				else
				{
					echo "Your email successfully varified.";
				}
			}
			else
			{
				echo "Your have already verify your email.";	
			}
		}
	}
}
else
{
	echo "Error occured. Please try again.";
}
?>

I hope that you may like my email verification in php tutorial. Please share it with your friends. If you have any question regarding this tutorial, you can ask me in comment as well as our email address codeandtuts@gmail.com. Thank you for reading this tutorial.

admin

HI, i am software developer having knowledge of PHP, C, C++ programming languages. I am very passionate about programming and ability to solve the programming problems. CodeandTuts is my blog where i like to put new tutorial and help new developer.

Leave a Reply

Your email address will not be published. Required fields are marked *