User Activation Email Sending Script in PHP

by Vincy. Last modified on July 6th, 2023.

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

The application will notify the user to activate his/her account. In this tutorial, we will see how to send a user activation email to notify the user.

Previously we have seen examples of creating a user registration system with HTML form and PHP. So, using the same example to make enhancements by sending an activation email on successful registration will be easy.

View Demo

If you read the linked article, it will help you follow the 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 and PHP codes created for sending the user activation email.

user activation mail

User Registration Form HTML Code

This form of HTML is already used in many user registration example codes. If you are already familiar with them, it will be good to recollect your idea about them to proceed further.

This form contains the 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 successful response after successful registration will be notified. These notifications are shown to the user on the browser. A notification message’s error or success type will be differentiated 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, 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

This section will show how to insert user data into the database once the validation is cleared. Before sending an email, the user activation link is formed using the $_SERVER global array indexes.

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

We email the registered user with an account activation link on successful user registration.

<?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, 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 the $_GET request method. About 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. It updates the user status column value to 1.

<?php
require_once __DIR__ . '/DataSource.php';
$database = new DataSource();
if (! empty($_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. You can run this example by importing this script to register users and send activation emails.

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(255) 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