User Activation Email Sending Script in PHP
Last modified on December 31st, 2018 by Vincy.
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.
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 href="style.css" type="text/css" rel="stylesheet" /> </head> <body> <form name="frmRegistration" method="post" action=""> <table border="0" width="500" align="center" class="demo-table"> <?php if(isset($message)) { ?> <div class="message <?php echo $type; ?>"><?php echo $message; ?></div> <?php } ?> <tr> <td width="28%">Username</td> <td><input type="text" class="demoInputBox" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName']; ?>"></td> </tr> <tr> <td>First Name</td> <td><input type="text" class="demoInputBox" name="firstName" value="<?php if(isset($_POST['firstName'])) echo $_POST['firstName']; ?>"></td> </tr> <tr> <td>Last Name</td> <td><input type="text" class="demoInputBox" name="lastName" value="<?php if(isset($_POST['lastName'])) echo $_POST['lastName']; ?>"></td> </tr> <tr> <td>Password</td> <td><input type="password" class="demoInputBox" name="password" value=""></td> </tr> <tr> <td>Confirm Password</td> <td><input type="password" class="demoInputBox" name="confirm_password" value=""></td> </tr> <tr> <td>Email</td> <td><input type="text" class="demoInputBox" name="userEmail" value="<?php if(isset($_POST['userEmail'])) echo $_POST['userEmail']; ?>"></td> </tr> <tr> <td>Gender</td> <td><input type="radio" name="gender" value="Male" <?php if(isset($_POST['gender']) && $_POST['gender']=="Male") { ?> checked <?php } ?>> Male <input type="radio" name="gender" value="Female" <?php if(isset($_POST['gender']) && $_POST['gender']=="Female") { ?> checked <?php } ?>> Female</td> </tr> <tr> <td></td> <td><input type="checkbox" name="terms"> I accept Terms and Conditions</td> </tr> </table> <div> <input type="submit" name="submit" value="Register" class="btnRegister"> </div> </form> </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"; } } } ?>
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 if(!isset($message)) { require_once("dbcontroller.php"); $db_handle = new DBController(); $query = "SELECT * FROM registered_users where email = '" . $_POST["userEmail"] . "'"; $count = $db_handle->numRows($query); if($count==0) { $query = "INSERT INTO registered_users (user_name, first_name, last_name, password, email, gender) VALUES ('" . $_POST["userName"] . "', '" . $_POST["firstName"] . "', '" . $_POST["lastName"] . "', '" . md5($_POST["password"]) . "', '" . $_POST["userEmail"] . "', '" . $_POST["gender"] . "')"; $current_id = $db_handle->insertQuery($query); 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!"; } } else { $message = "User Email is already in use."; $type = "error"; } } ?>
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."; } } ?>
DBController Class
The database related operations are handled by using the DBController class. The database configurations are set as the class properties. The class constructor establishes connection and set the connection object $conn.
<?php class DBController { private $host = "localhost"; private $user = "root"; private $password = "test"; private $database = "phppot_examples"; private $conn; function __construct() { $this->conn = $this->connectDB(); } function connectDB() { $conn = mysqli_connect($this->host,$this->user,$this->password, $this->database); return $conn; } function runQuery($query) { $result = mysqli_query($this->conn, $query); while($row=mysqli_fetch_assoc($result)) { $resultset[] = $row; } if(!empty($resultset)) return $resultset; } function numRows($query) { $result = mysqli_query($this->conn, $query); $rowcount = mysqli_num_rows($result); return $rowcount; } function updateQuery($query) { $result = mysqli_query($this->conn, $query); if (!$result) { die('Invalid query: ' . mysqli_error($this->conn)); } else { return $result; } } function insertQuery($query) { $result = mysqli_query($this->conn, $query); if (!$result) { die('Invalid query: ' . mysqli_error($this->conn)); } else { return mysqli_insert_id($this->conn); } } function deleteQuery($query) { $result = mysqli_query($this->conn, $query); if (!$result) { die('Invalid query: ' . mysqli_error($this->conn)); } else { return $result; } } } ?>
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`) )
Popular Articles
Double Opt-In Subscription Form with Secure Hash using PHP
User Registration and Login Authentication Code using PHP
Double Opt-In Subscription Form with Secure Hash using PHP
PHP User Registration Form (Sign up) with MySQL Database
Material Design Login Form with PHP and jQuery
User Activation Email Sending Script in PHP
How to Convert Text to Image using PHP
PHP Price Range Search using jQuery Slider
I’m Vincy, a web developer. If you want to start a project and do a quick launch, contact me.
I am available for freelance work.
Featured Product
Trending Now
How to Become a Full Time Freelance PHP Developer and Consultant
jQuery AJAX Inline CRUD with PHP
Simple Secure Spam-Free Contact Form in PHP – Iris
Testimonials
“The process was fast and very professional. The whole time we could follow the work and correct small details. As we got new ideas under the process Vincy was able to implement them without delay ...”
Steen Hertzum Kirchhoff, JobRater, Sweeden
Looking for an expert PHP freelancer?
Do you want to develop a modern, lightweight, responsive web application and launch quickly?
Email:
Digital Goods Shop
FAQ Support Policy Refund Policy Licenses User License Developer License
Comments
Post a Comment