User Account activation, email verification using PHP, MySQL and Swiftmailer
Introduction:
I have posted tutorials on login registration system, which has
simple account registration process to just enter the details to create
new account and you can login to the account, but we always needs to
verify account email under live application to make sure user is using
live email account for further use.
I am writing this tutorial for those users who want to implement email activation feature in to the PHP application.
Please make sure we will be using Swiftmailer to send emails, if you
are not familiar with swiftmailer you can read the following tutorial to
read about sending emails using swiftmailer : PHP Email Sending with
SwiftMailer
This tutorial is having following features:
Register New User
Send account activation email with verification link
Verify user with verification link
User login
Technology used:
PHP
MySQL
Bootstrap 3.3.7
Swift Mailer
Let’s get started:
Step 1: Application Directory and Database setup
First step is to setup application directly under web application
directory, it can be anything it is totally depend on your Operating
System and work environment setup.
I am going to assume that you have created a empty directory to use for our login registration application.
Second step is to create new MySQL database with users table to use a
backend for this application, if you already having a database setup
then you can skip this step.
Use following command to create you database:
1
create database`itechempires_dev`;
You can replace the database name with whatever you suggest just make
sure to keep this in mind to replace while connecting from PHP script,
now let’s create users tables with required fields.
Use following SQL query to create new table called users:
1
2
3
4
5
6
7
8
9
10
11
CREATETABLE`users`(
`id`int(11)NOTNULLAUTO_INCREMENT,
`first_name`varchar(30)NOTNULL,
`last_name`varchar(30)NOTNULL,
`email`varchar(100)NOTNULL,
`password`varchar(250)NOTNULL,
`status`int(11)NOTNULLDEFAULT'0',
`email_activation_key`varchar(100)NOTNULL,
PRIMARYKEY(`id`),
UNIQUEKEY`email`(`email`)
)ENGINE=InnoDBDEFAULTCHARSET=latin1;
Users Table Design Overview
A quick overview on important fields of the table:
id : Primary key with auto increment
status: not null default is set to 0, zero means a user is inactive
email_activation_key : this field is going to have temporary activation code will be using it while doing verification process.
Step 2: Design Registration and Login Forms:
Before going to start designing we will need to download bootstrap framework from getbootstrap.com,
please visit the site and download required version of bootstrap
framework. It is good practice to use design frameworks while developing
the web application it helps to boost our development process bootstrap
is one of the best example.
If you’re done with the download extract the file and copy and paste bootstrap-3.3.7-dist folder to your application directory.
Create new index.php page and use following script:
If you try to run this script on web browser you will see I have
added two forms on single page as you know this a just demo to learn you
can have two separate pages for each request, just make sure about the
form action.
Let’s have a quick look on our forms: Register: Registration FormLogin: Login Form
Step 3: Create Database connection script:
This is very basic step but required, we needs to create new file and
add database connection script to be able to connect to the database
whenever required.
Create new file called script/database_connection.php and add following script, please make sure to update required variable to match with your system configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
/**
* Tutorial: PHP Account Activation/verification
*
* File: Database Configuration
*/
// database Connection variables
define('HOST','localhost');// Database host name ex. localhost
define('USER','root');// Database user. ex. root ( if your on local server)
define('PASSWORD','secret');// Database user password (if password is not set for user then keep it empty )
define('DATABASE','ADD_DATABASE_NAME_HERE');// Database name
functionDB()
{
$con=newmysqli(HOST,USER,PASSWORD,DATABASE);
if($con->connect_error){
die("Connection failed: ".$con->connect_error);
}
return$con;
}
?>
Step 4: Install swiftmailer:
As I said we would be using swiftmailer for outgoing emails, so in this step we will install swiftmailer to the application
There are few different ways to install swiftmailer to
the application here I will be using composer to get that pulled in, if
you don’t have composer installed I would suggest to install composer or
clone swiftmailer from Github repository. If you still don’t want to do
both of the above steps you can simple download it from the Github,
anyways let’s install it by using composer
Open Terminal/command line and use following command to install swiftmailer library:
1
composer require swiftmailer/swiftmailer@stable
If you are getting output similar to below lines, meaning composer is downloading required package files.
1
2
3
4
5
6
7
8
./composer.json has been created
Loading composer repositories with packageinformation
Updating dependencies(including require-dev)
-Installing swiftmailer/swiftmailer(v5.4.3)
Loading from cache
Writing lock file
Generating autoload files
We have swiftmailer ready to use, move on to the next step to create library file.
Step 5: Create Library with necessary Functions:
We have our basic forms, database connection script and swiftmailer
ready to use, now we will be using a central library file with class and
functions to use while creating user, login user and send activation
email.
Go ahead and create file in the application called lib/library.php,
make sure to add this under lib folder just to keep this practice in
hand to have better management of our source, all right so we have
library.php file ready to use:
Add a following script to it, which is have functions to Register new User, Login active user, Send activation email and so on.
$query="SELECT `id` FROM `users` WHERE `email` = '$email' AND status = 1";
if(!$result=mysqli_query($this->db,$query)){
exit(mysqli_error($this->db));
}
if(mysqli_num_rows($result)>0){
returnTRUE;
}else{
returnFALSE;
}
}
/**
* get user details
*
* @param $id
*
* @return array|null
*/
publicfunctionUserDetails($id)
{
$id=mysqli_real_escape_string($this->db,$id);
$query="SELECT `first_name`, `last_name`, `email` FROM `users` WHERE `id` = '$id'";
if(!$result=mysqli_query($this->db,$query)){
exit(mysqli_error($this->db));
}
$data=[];
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_assoc($result)){
$data=$row;
}
}
return$data;
}
}
?>
Detail Description:
If you have a look on above file we have several functions in the library to perform operations: Register(): used to create a new users, it requires four parameters first_name, last_name, email and password after creating new user it is going to call another function to send activation email. sendEmail(): used to send activation
email to the user using swiftmailer, please make sure to change required
user email and password under SMTP settings. isEmail(): to check whether email is
exists in the application, this is going to be usefull while creating
new user as well as login existing user. getUserID(): use to get user ID from the database by using activation key which we are going to send with the email while creating new user. getUserIDByEmail(): as name suggest, it used to get User ID by using user email address. activateAccount(): used to activate the user by using User ID, we are going to call this function from activation.php page. isValidPassword(): validated the given password while login, we are using password_verify() function to validated the password which is encrypted by password_hash() function. findPasswordByEmail(): finding the encrypted password by email. isActive(): check whether given email address is active or inactive. UserDetails(): used to get user details to display on profile page.
Step 6: Add required HTML email files:
If you check sendEmail() function you will see that we
need html and plain text content while sending email from swiftmailer,
this files are going to have the email content along with the activation
link.
Go ahead and create following files and add give source to it: email/email_verification.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
h1, h4 {
color:#ff4500;
}
.header {
border-bottom:2pxsolid#ff4500;
background-color:#fff;
text-align:center;
}
.footer {
border-top:2pxsolid#1b6d85;
}
.footer > a {
color:#ff4500;
}
</style>
</head>
<body>
<table width="100%">
<tr>
<td align="center">
<table width="600">
<tr>
<td class="header">
<h1>iTech Empires</h1>
</td>
</tr>
<tr>
<td>
<h2>Verify Your Email Address</h2>
<p>Thanks forcreating an account with the verification demo tutorial.
Please follow the link below toverify your email address.</p>
You can change the content as per you requirement.
Step 7: Register User:
Open up the index.php file, which is having login and register form, let’s add register feature there.
Add following line of code at the top of the index.php page.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
// Start Session
session_start();
// Application library ( with DemoLib class )
require__DIR__.'/lib/library.php';
$app=newDemoClass();
$login_error_message='';
$register_error_message='';
$register_success_message='';
// check Register request
if(!empty($_POST['btnRegister'])){
// validated user input
if($_POST['first_name']==""){
$register_error_message='First name field is required!';
}elseif($_POST['last_name']==""){
$register_error_message='Last name field is required!';
}elseif($_POST['email']==""){
$register_error_message='Email field is required!';
}elseif($_POST['password']==""){
$register_error_message='Password field is required!';
// show success message and ask user to check email for verification link
$register_success_message='Your account is created successfully, please check your email for verification link to activate your account.';
}
}
}
?>
if you try to run the current code you should be able to create new user:
You should get the email similar following email into your mailbox,
verification links key should be different as it is randomly generated
from the script. Activation Email
Step 8: Create Activation Page:
We have added the activation.php page into the email link now we need to create the page to handle the activation request.
activation page is going to access the input request from URL with the variable name called key and it is going to check the user associted and update the status field is equal to 1 to say it is activate.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
if(!empty($_GET['key'])&&isset($_GET['key'])){
require__DIR__.'/lib/library.php';
$app=newDemoClass();
$id=$app->getUserID($_GET['key']);
if($id!=''){
// activate user
$app->activateAccount($id);
echo'Your account is activated, please <a href="index.php">click here</a> to to login';
}else{
echo"Invalid activation key!";
}
}else{
echo"Invalid activation key!";
}
?>
If you try to click on the email link to test, this page needs work and it is going to show you a following response:
We are almost done with the registration and activation part, let’s focus on to the login request.
Step 9: Handle Login Request:
Open up the index.php page into your editor and add following code to validate and handle the login request.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// check Login request
if(!empty($_POST['btnLogin'])){
$email=trim($_POST['email']);
$password=trim($_POST['password']);
if($email==""){
$login_error_message='Email field is required!';
}elseif($password==""){
$login_error_message='Password field is required!';
$_SESSION['user_id']=$app->getUserIDByEmail($email);// Set Session
header("Location: profile.php");// Redirect user to the profile.php
}else{
$login_error_message='Your account is not activated yet, please check your email to activate your account!';
}
}else{
$login_error_message='Invalid login password!';
}
}else{
$login_error_message='Account is not exist with this email, please create new account to login!';
}
}
}
if you see the above code we are validating the user with the
several conditions, please keep in mind that this is just a part of code
from our existing index.php page, so needs to call the library file
again as we have already added on top of the page.
Step 10: Create Profile Page:
Create profile.page page to show user details and logout link:
Account activation process with email verification using PHP,MySQL andSwiftmailer
</h2>
</div>
</div>
<div class="form-group">
Note:Thisisdemo version from iTech Empires tutorials.
</div>
<div class="row">
<div class="col-md-12 well">
<h4>UserProfile</h4>
<h4>Welcome<?phpecho$user['first_name'];?></h4>
<p>Account Details:</p>
<p>First Name:<?phpecho$user['first_name'];?></p>
<p>LastName<?phpecho$user['last_name'];?></p>
<p>Email<?phpecho$user['email'];?></p>
<br>
Click here to<ahref="logout.php">Logout</a>
</div>
</div>
</div>
</body>
</html>
Step 11: Logout page:
Finally use following script to create logout.php page to clear session and logout the user.
1
2
3
4
5
6
7
8
9
10
11
12
<?php
// start session
session_start();
// Destroy user session
unset($_SESSION['user_id']);
// Redirect to index.php page
header("Location: index.php");
?>
Tutorial Folder Structure:
We are done!
If you get any question or issues related to this tutorial you can
always let me know using comment box below or you can also send me an
direct email using contact us page, thank you!