User Activation Email Sending Script in PHP

Last modified on February 24th, 2017 by Vincy.

In this tutorial, we are going to see how to send user activation email after user registration. In the previous tutorial, we have seen the code for adding a new user to our database with a registration form example.

In this example, we are using the same code with slight modification. We have added duplicate email validation code before adding the user to the database. And then, we are sending an activation email to the registered user’s email address.

View DemoDownload


PHP Duplicate Email Validation

This is for checking if the registered user’s email is already in use.

$query = "SELECT * FROM registered_users where email = '" . $_POST["userEmail"] . "'";
$count = $db_handle->numRows($query);
if($count==0) {
	// Add new user to database
} else {
	$message = "User Email is already in use.";	

Sending Activation Email

After email duplicate validation, and if it is not in use, we are executing the insert query to add the new user. On successful user registration, we are sending an email to the registered user with an account activation link. The code is,

$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.";	

User Account Activation in PHP

On clicking the user account activation link from the email, this code will be executed to update registered user status as active.

	$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.";

View DemoDownload

This PHP code tutorial was published on November 23, 2014.

↑ Back to Top

Share this Article