User Activation Email Sending Script in PHP

by Vincy. Last modified on November 8th, 2022.

User activation email sending is a most common requirement for the web application containing user registration system. Generally, the user’s default status will be inactive on registering with an application.

The application will send notification for the user to activate his/her account. In this tutorial, we are going to see how to send user activation email to send the notification for the user.

Previously we have seen examples to create user registration system with HTML form and PHP. So, it will be easy to use the same example to make enhancement of sending activation email on successful registration.

If you read the linked article, then it will help you to follow this example code I have used in this article.

In this example, I have added the server-side form validation script to validate the user email and other fields before saving it to the database.

Also, the email id duplication check is done by comparing the form data and the database. Let us see the HTML, PHP codes that are created for sending the user activation email.

View Demo

User Email Notification

User Registration Form HTML Code

This form HTML is already used in may user registration example code. If you already familiar with then it will be good to recollect your idea about it to proceed further.

This form contains input to collect user data like name, email, password and more details. These fields are validated on the server side using PHP.

The validation error messages or the success response after successful registration will be notified. These notifications are shown to the user on the browser. The error or success type of a notification message will be differentiated by using simple CSS styles.

<html>
<head>
<title>PHP User Registration Form</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/form.css" />
<style>
.gender-radio {
    width: auto;
}

#loader-icon {
    margin-left: 80px;
    display: none;
}
</style>
<script>

</script>
</head>
<body>
    <div class="phppot-container">
        <form name="frmRegistration" method="post" action="">
<?php if(isset($message)) { ?>
<div class="message <?php echo $type; ?>"><?php echo $message; ?></div>
<?php } ?>
<h2>User Activation Email</h2>
            <div class="row">
                <label>Username</label> <input type="text"
                    name="userName"
                    value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>">
            </div>
            <div class="row">
                <label> First Name</label> <input type="text"
                    name="firstName"
                    value="<?php if(isset($_POST['firstName'])) echo $_POST['firstName']; ?>">
            </div>
            <div class="row">
                <label>Last Name</label> <input type="text"
                    name="lastName"
                    value="<?php if(isset($_POST['lastName'])) echo $_POST['lastName']; ?>">
            </div>
            <div class="row">
                <label>Password</label> <input type="password"
                    name="password" value="">
            </div>
            <div class="row">
                <label>Confirm Password</label> <input type="password"
                    name="confirm_password" value="">
            </div>
            <div class="row">
                <label>Email</label> <input type="text" name="userEmail"
                    value="<?php if(isset($_POST['userEmail'])) echo $_POST['userEmail']; ?>">
            </div>
            <div class="row">
                <input type="radio" name="gender" value="Male"
                    class="gender-radio"
                    <?php if(isset($_POST['gender']) && $_POST['gender']=="Male") { ?>
                    checked <?php  } ?>> Male<input type="radio"
                    name="gender" value="Female" class="radio-align gender-radio"
                    <?php if(isset($_POST['gender']) && $_POST['gender']=="Female") { ?>
                    checked <?php  } ?>> Female
            </div>
            <div class="row">
                <input type="checkbox" name="terms"> I accept Terms and
                Conditions
            </div>
            <div class="row">
                <input type="submit" name="submit" id="btn-submit"
                    value="Register" onclick="showLoader();">
            </div>
            <div id="loader-icon" class="loader">
                <img src="loader.gif" />
            </div>
        </form>
    </div>
    <script>
    function showLoader() {
        document.getElementById("loader-icon").style.display = 'block';
        document.getElementById("btn-submit").style.display = 'none';
    }
    }
    </script>
</body>
</html>

PHP Form and Email Uniqueness Validation

This PHP code contains consecutive conditional statements to validate all the registration form fields. Once the validation is done, then the user email uniqueness will be tested by comparing the existing emails of the user database.

<?php
if (count($_POST) > 0) {
    /* Form Required Field Validation */
    foreach ($_POST as $key => $value) {
        if (empty($_POST[$key])) {
            $message = ucwords($key) . " field is required";
            $type = "error";
            break;
        }
    }
    /* Password Matching Validation */
    if ($_POST['password'] != $_POST['confirm_password']) {
        $message = 'Passwords should be same<br>';
        $type = "error";
    }

    /* Email Validation */
    if (! isset($message)) {
        if (! filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) {
            $message = "Invalid UserEmail";
            $type = "error";
        }
    }

    /* Validation to check if gender is selected */
    if (! isset($message)) {
        if (! isset($_POST["gender"])) {
            $message = " Gender field is required";
            $type = "error";
        }
    }

    /* Validation to check if Terms and Conditions are accepted */
    if (! isset($message)) {
        if (! isset($_POST["terms"])) {
            $message = "Accept Terms and conditions before submit";
            $type = "error";
        }
    }

    if (! isset($message)) {
        require_once __DIR__ . '/DataSource.php';
        $database = new DataSource();
        $query = "SELECT * FROM registered_users where email = ?";
        $paramType = 's';
        $paramValue = array(
            $_POST["userEmail"]
        );
        $count = $database->getRecordCount($query, $paramType, $paramValue);

        if ($count == 0) {
            // Insert and send activation email
        } else {
            $message = "User Email is already in use.";
            $type = "error";
        }
    }
}
?>

User Activation Email Sending Script

In this section, we will see how to insert user data into the database once the validation is cleared. Before sending email, the user activation link is formed by using the $_SERVER global array indexes.

In this code, I have used PHP mail function to send the user activation email. If you want to send an email with PHPMailer then refer the linked article.

On successful user registration, we are sending an email to the registered user with an account activation link.

<?php
$hashedpassword = password_hash(($_POST["password"]), PASSWORD_DEFAULT);
$query = "INSERT INTO registered_users (user_name, first_name, last_name, password, email, gender) VALUES (?, ?, ?, ?, ?, ?)";
$paramType = 'ssssss';
$paramValue = array(
    $_POST["userName"],
    $_POST["firstName"],
    $_POST["lastName"],
    $hashedpassword,
    $_POST["userEmail"],
    $_POST["gender"]
);
$current_id = $database->insert($query, $paramType, $paramValue);
if (! empty($current_id)) {
    $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" . "activate.php?id=" . $current_id;
    $toEmail = $_POST["userEmail"];
    $subject = "User Registration Activation Email";
    $content = "Click this link to activate your account. <a href='" . $actual_link . "'>" . $actual_link . "</a>";
    $mailHeaders = "From: Admin\r\n";
    if (mail($toEmail, $subject, $content, $mailHeaders)) {
        $message = "You have registered and the activation mail is sent to your email. Click the activation link to activate you account.";
        $type = "success";
    }
    unset($_POST);
} else {
    $message = "problem in registration. Try Again!";
}
?>

User Account Activation Code in PHP

This is the activate.php code which will be executed by clicking the activation link sent through the email. The activation link will contain the user id in its query string.

This id will be received in activate.php by using $_GET request method. With the reference of this user id, the UPDATE query will be created to change the status of the user account.

Initially, the status field will be empty, whereas it will be turned to active after activation.

<?php
	require_once("dbcontroller.php");
	$db_handle = new DBController();
	if(!empty($_GET["id"])) {
	$query = "UPDATE registered_users set status = 'active' WHERE id='" . $_GET["id"]. "'";
	$result = $db_handle->updateQuery($query);
		if(!empty($result)) {
			$message = "Your account is activated.";
		} else {
			$message = "Problem in account activation.";
		}
	}
?>

Activate user account by clicking the mail activation link

This script is called on clicking the activation link on the mail sent after signup. It updates the status of the user account entry by the record id.

<?php
require_once __DIR__ . '/DataSource.php';
$database = new DataSource();
if (! empty($_GET["id"])) {
    $query = "UPDATE registered_users set status = 'active' WHERE id='" . $_GET["id"] . "'";

    $query = "UPDATE registered_users set status = ? WHERE id = ?";
    $paramType = 'si';
    $status = active;
    $paramValue = array(
        $status,
        $_GET["id"]
    );
    $result = $database->update($query, $paramType, $paramValue);
    if (! empty($result)) {
        $message = "Your account is activated.";
        $type = "success";
    } else {
        $message = "problem in account activation.";
        $type = "error";
    }
}
?>
<html>
<head>
<title>PHP User Activation</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<?php if(isset($message)) { ?>
    <div class="message <?php echo $type; ?>"><?php echo $message; ?></div>
    <?php } ?>
</body>
</html>

Database Script

The following database script shows the create statement for the registered_user table. By importing this script you can run this example to register users and send user activation email.

CREATE TABLE IF NOT EXISTS `registered_users` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `password` varchar(25) NOT NULL,
  `email` varchar(55) NOT NULL,
  `gender` varchar(20) NOT NULL,
  `status` varchar(10) NOT NULL DEFAULT 'Inactive',
  PRIMARY KEY (`id`)
)

View DemoDownload

↑ Back to Top

Share this page