Email Activation Code in PHP

Photo of Mike Dalisay
Modified Sunday, September 15, 2013
by - @ninjazhai
Email activation or verification is one requirement when you're building an app with a membership feature. 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.

php script for email verification

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.


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 terms, have you ever seen a "Login with Facebook" button? 

We see one in StackOverflow login:

Unfortunately, we don't cover OAuth login in this post, but don't be sad, I might do those kinds of post in a simplified way too.

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:

Step 5 happens in our activate.php

Let's Code!

Alright, so the technologies used in this code are mostly PHP and MySQL. 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.

libs/db_connect.php - for database connection, you know what it looks like, right? 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,
  PRIMARY KEY  (`id`)

sign_up.php - where the sign up form and processing of user input is located.

// if the sign up form was submitted
    $email = isset($_POST['email']) ? $_POST['email'] : "";

    // posted email must not be empty
        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>";

        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);
        $num = $stmt->rowCount();
            echo "<div>Your email is already activated.</div>";
            // 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);
            $num = $stmt->rowCount();
                // you have to create a resend verification script
                echo "<div>Your email is already in the system but not yet verified. <a href='resend.php'>Resend verification?</a>.</div>";
                // 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 = "" . $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='' target='_blank'>The Code of a Ninja</a><br />";
                $name = "The Code of a Ninja";
                $email_sender = "";
                $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, verified = '0' means it is unverified, on activation, it becomes '1'
                    $query = "INSERT INTO 
                                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
                        // echo "<div>Unverified email was saved to the database.</div>";
                        echo "<div>Unable to save your email to the database. <a href''>Tell Mike.</a></div>";
                    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>";

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

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']);
$num = $stmt->rowCount();


    // 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']);

        // tell the user
        echo "<div>Your email is valid, thanks!. You may now login.</div>";
        echo "<div>Unable to update verification code.</div>";
    // tell the user he should not be in this page
    echo "<div>I think you're in the wrong place.</div>";

Code Download

I provided a download link for you just in case you want to have a copy of the code we discussed. Free code download here.

Live Demo

Please note that this demo is really live, if you enter your email, received an email with the activation link and clicked it, you're subscribed here in our code blog. See the live demo here.

Thanks for reading this email activation PHP script!
For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.