User Activation Email Sending Script in PHP

In this tutorial we are going to see how to send user activation email after user registration. In previous tutorial, we have seen the code for adding 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 user to database. And then, we are sending activation email to the registered user’s email address.

View DemoDownload

activation-mail

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 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.";	
	}
	unset($_POST);
}

User Account Activation in PHP

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

<?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.";
		}
	}
?>

View DemoDownload

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

↑ Back to Top