Email Activation Code in PHP

Email activation or verification is one requirement when you’re building an app with a membership feature. Our Email Activation Code in PHP will help you with that!

This is one way to detect if there’s really a person behind the submitted email address. An email address is considered invalid if no person was able to open it and click the activation link.

Although nowadays, there are some alternative ways to verify the validity of an email address or user. Some systems prefer the old school method, like what this post covers.

Email Activation Code in PHP

OAuth

The alternative way I was talking about is by using a social network login. Facebook, Twitter, Google+ and even Microsoft is providing something called an OAuth (Open Authorization) login.

In simple scenario, have you ever seen a "Login with Facebook" button? We see one in StackOverflow login:

oauth-login-email-validation

Unfortunately, we don't cover OAuth login in this post.

Basic Flow

The following steps shows the basic flow how email activation works.

  1. User fills up your sign up or registration form and submit it to the system.
  2. System generates unique activation code which acts like a “key”
  3. System sends a link with the activation code to the email provided during the sign up form.
  4. User opens his email inbox, found the system email and click the link with the activation code. This is like using the “key” to “unlock the door” which represents your application.
  5. User was sent to a link saying ‘email was activated’

Where are these happening?

To give you a clearer picture where in our code the steps above happens:

Steps 1 to 3 happens in sign_up.php.

Step 4 happens in the user’s email provider such as GMail, Y! Mail, etc. User should receive something like this:

email-verification-link-sent

Step 5 happens in our activate.php

Let’s Code!

Alright, so the technologies used in this code are mostly PHP and MySQL.

Create your database and name it 'email_activation_db'. Here’s the database table structure that can be used, we name it as the ‘users’ table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nickname` varchar(32) NOT NULL,
  `email` varchar(264) NOT NULL,
  `verified` int(11) NOT NULL COMMENT '0=no, 1=yes',
  `verification_code` varchar(264) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
 
INSERT INTO `users` (`id`, `nickname`, `email`, `verified`, `verification_code`, `created`, `modified`) VALUES
(135, '', '[email protected]', 1, '2e729fe3ded03c139b289213db2b3159', '2016-08-13 16:42:28', '2016-08-13 08:42:46');

libs/db_connect.php – for database connection, this file has the following code:

<?php
$host = "localhost";
$db_name = "email_activation_db";
$username = "root";
$password = "";
 
try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
    echo "Connection error: " . $exception->getMessage();
}
?>

sign_up.php – where the sign up form and processing of user input is located. The following code is inside sign_up.php file.

<?php
// if the sign up form was submitted
if($_POST){
 
    $email = isset($_POST['email']) ? $_POST['email'] : "";
 
    // posted email must not be empty
    if(empty($email)){
        echo "<div>Email cannot be empty.</div>";
    }
 
    // must be a valid email address
    else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        echo "<div>Your email address is not valid.</div>";
    }
 
    else{
 
        include 'libs/db_connect.php';
 
        // check first if record exists
        $query = "SELECT id FROM users WHERE email = ? and verified = '1'";
        $stmt = $con->prepare( $query );
        $stmt->bindParam(1, $email);
        $stmt->execute();
        $num = $stmt->rowCount();
 
        if($num>0){
            echo "<div>Your email is already activated.</div>";
        }
 
        else{
 
            // check first if there's unverified email related
            $query = "SELECT id FROM users WHERE email = ? and verified = '0'";
            $stmt = $con->prepare( $query );
            $stmt->bindParam(1, $email);
            $stmt->execute();
            $num = $stmt->rowCount();
 
            if($num>0){
 
                // you have to create a resend verification script
                echo "<div>Your email is already in the system but not yet verified.</div>";
            }
 
            else{
 
                // now, compose the content of the verification email, it will be sent to the email provided during sign up
                // generate verification code, acts as the "key"
                $verificationCode = md5(uniqid("yourrandomstringyouwanttoaddhere", true));
 
                // send the email verification
                $verificationLink = "https://codeofaninja.com/demos/php-examples/email-activation-php-script/activate.php?code=" . $verificationCode;
 
                $htmlStr = "";
                $htmlStr .= "Hi " . $email . ",<br /><br />";
 
                $htmlStr .= "Please click the button below to verify your subscription and have access to the download center.<br /><br /><br />";
                $htmlStr .= "<a href='{$verificationLink}' target='_blank' style='padding:1em; font-weight:bold; background-color:blue; color:#fff;'>VERIFY EMAIL</a><br /><br /><br />";
 
                $htmlStr .= "Kind regards,<br />";
                $htmlStr .= "<a href='https://codeofaninja.com/' target='_blank'>The Code of a Ninja</a><br />";
 
 
                $name = "The Code of a Ninja";
                $email_sender = "[email protected]";
                $subject = "Verification Link | The Code Of A Ninja | Subscription";
                $recipient_email = $email;
 
                $headers  = "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                $headers .= "From: {$name} <{$email_sender}> \n";
 
                $body = $htmlStr;
 
                // send email using the mail function, you can also use php mailer library if you want
                if( mail($recipient_email, $subject, $body, $headers) ){
 
                    // tell the user a verification email were sent
                    echo "<div id='successMessage'>A verification email were sent to <b>" . $email . "</b>, please open your email inbox and click the given link so you can login.</div>";
 
 
                    // save the email in the database
                    $created = date('Y-m-d H:i:s');
 
                    //write query
                    $query = "INSERT INTO
                                users
                            SET
                                email = ?,
                                verification_code = ?,
                                created = ?,
                                verified = '0'";
 
                    $stmt = $con->prepare($query);
 
                    $stmt->bindParam(1, $email);
                    $stmt->bindParam(2, $verificationCode);
                    $stmt->bindParam(3, $created);
 
                    // Execute the query
                    if($stmt->execute()){
                        // echo "<div>Unverified email was saved to the database.</div>";
                    }else{
                        echo "<div>Unable to save your email to the database.";
                        //print_r($stmt->errorInfo());
                    }
 
                }else{
                    die("Sending failed.");
                }
            }
 
 
        }
 
    }
 
}
 
// show your sign up or registration form
echo "<form action='" . $_SERVER['PHP_SELF'] . "' method='post'>";
    echo "<input type='email' name='email' placeholder='Enter your email address to subscribe' required />";
    echo "<input type='submit' value='Subscribe' />";
echo "</form>";
?>

For sending the verification email, we used the PHP mail() function but you can also use a library like PHPMailer if you want to use SMTP such as of GMail.

activate.php – it has one job, update the the unverified to verified email address.

<?php
include 'libs/db_connect.php';
 
// check first if record exists
$query = "SELECT id FROM users WHERE verification_code = ? and verified = '0'";
$stmt = $con->prepare( $query );
$stmt->bindParam(1, $_GET['code']);
$stmt->execute();
$num = $stmt->rowCount();
 
if($num>0){
 
    // update the 'verified' field, from 0 to 1 (unverified to verified)
    $query = "UPDATE users
                set verified = '1'
                where verification_code = :verification_code";
 
    $stmt = $con->prepare($query);
    $stmt->bindParam(':verification_code', $_GET['code']);
 
    if($stmt->execute()){
        // tell the user
        echo "<div>Your email is valid, thanks!. You may now login.</div>";
    }else{
        echo "<div>Unable to update verification code.</div>";
        //print_r($stmt->errorInfo());
    }
 
}else{
    // tell the user he should not be in this page
    echo "<div>We can't find your verification code.</div>";
}
?>

Live Demo

Please note that this demo is live. If you enter your email and click the subscribe button, you will receive an email with the activation link. If you click it, you will be subscribed here in our code blog.

Download Email Activation Code in PHP

You can get the source code by following the whole, well detailed tutorial above.

But isn’t it more convenient if you can just download the complete source code we used, and play around it?

The source code of this tutorial is part of our 30+ useful Web Programming source code package. Each item in the package has its own tutorial like the one above.

If you are just starting out to learn web programming and serious about learning more, this is the right package for you. Click green button below to see the what is included in the package and download it there.


Need email activation code only? But the code now using the green button below.

Related Source Code

You can download our PHP Login System & User Management Module as well. This source code is about PHP Login System.

It will help you understand how to login and logout functionality works. Sign up email verification, user registration, and forgot password features are included as well.

Thanks for studying our email activation code in PHP!

Hi! I'm Mike Dalisay, the co-founder of codeofaninja.com, a site that helps you build web applications with PHP and JavaScript. Need support? Comment below or contact [email protected]

I'm also passionate about technology and enjoy sharing my experience and learnings online. Connect with me on LinkedIn, Twitter, Facebook, and Instagram.