Building A registration System with Email verification in PHP
by Hyder on April 1, 2010
in PHP
Have you ever registered on a website and you were required to activate your newly created account via a confirmation link sent to the email address you supplied while registering? This Email verification “Mechanism” is very common nowadays especially in forums, popular websites such as ebay, paypal, Facebook etc .Verifying Email Address helps to reduce spam and also to make sure that the email supplied belongs to that member.
What are we going to build ?
We are going to build a small system in which a user can register a new account. After registration, a confirmation link will be emailed to the email supplied in the registration form. The user will have to log in his email Account and click the activation link. After that, He or she or she will be able to login into the system. Before Going into the code, here is some screenshot of how it is going to work.


After Successful registration, an Activation will be emailed to the user in order to verify that the email address supplied is really his.

On Clicking the Activation link , A message will be displayed whether Account has been Activated successfully or not.

The user may now login .

If Login is successful, He or she will be redirected to page.php, which could be called the “member Area”

Step 1: Database Connection File
This file contains the Database Connection Information. It Also contains the Sender’s email address,website url and the smtp server address. Please change these settings accordingly. IF you are going to host this script on a server at hostgator , namecheap , godaddy etc , there’s a great chance you would not need the “SMTP” part .Simply Remove this line of code.
03 |
/*Define constant to connect to database */ |
04 |
DEFINE( 'DATABASE_USER' , 'root' ); |
05 |
DEFINE( 'DATABASE_PASSWORD' , '' ); |
06 |
DEFINE( 'DATABASE_HOST' , 'localhost' ); |
07 |
DEFINE( 'DATABASE_NAME' , 'forum' ); |
08 |
/*Default time zone ,to be able to send mail */ |
09 |
date_default_timezone_set( 'UTC' ); |
11 |
/*You might not need this */ |
12 |
ini_set ( 'SMTP' , "mail.myt.mu" ); |
13 |
// Overide The Default Php.ini settings for sending mail |
15 |
//This is the address that will appear coming from ( Sender ) |
16 |
define( 'EMAIL' , '
Данный адрес e-mail защищен от спам-ботов, Вам необходимо включить Javascript для его просмотра.
' ); |
18 |
/*Define the root url where the script will be found such as |
22 |
// Make the connection: |
23 |
$dbc = @mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, |
27 |
trigger_error( 'Could not connect to MySQL: ' . mysqli_connect_error()); |
Database Structure

02 |
-- Table structure for table `members` |
05 |
CREATE TABLE IF NOT EXISTS `members` ( |
06 |
`Memberid` int (10) NOT NULL AUTO_INCREMENT, |
07 |
`Username` varchar (20) NOT NULL , |
08 |
`Email` varchar (20) NOT NULL , |
09 |
` Password ` varchar (10) NOT NULL , |
10 |
`Activation` varchar (40) DEFAULT NULL , |
11 |
PRIMARY KEY (`Memberid`) |
12 |
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=22 ; |
Step 2 : Registration Page
The CSS Part has been omitted here . You can read a detailed description of how this form has been built using pure css .
01 |
< form action = "index.php" method = "post" class = "registration_form" > |
03 |
< legend >Registration Form </ legend > |
05 |
< p >Create A new Account < span style = "background:#EAEAEA none repeat scroll 0 0;line-height:1;margin-left:210px;;padding:5px 7px;" > |
06 |
Already a member? < a href = "login.php" >Log in</ a ></ span > </ p > |
08 |
< div class = "elements" > |
09 |
< label for = "name" >Name :</ label > |
10 |
< input type = "text" id = "name" name = "name" size = "25" /> |
12 |
< div class = "elements" > |
13 |
< label for = "e-mail" >E-mail :</ label > |
14 |
< input type = "text" id = "e-mail" name = "e-mail" size = "25" /> |
16 |
< div class = "elements" > |
17 |
< label for = "Password" >Password:</ label > |
18 |
< input type = "password" id = "Password" name = "Password" size = "25" /> |
21 |
< input type = "hidden" name = "formsubmitted" value = "TRUE" /> |
22 |
< input type = "submit" value = "Register" /> |
Code to Handle the Registration Form Submission :
Basic Form Validation Rules :
- Make sure no field is empty .
- Validate Email Address Format .
If Form Validation is successfull a unique activation code is created using the php built in function MD5 () .For each new account , a unique activation key is sent along the email address of the member.The md5 key is then added to the database field “Activation” .
The Activation Link is in this format :
http://website.com/activate.php?email=
Данный адрес e-mail защищен от спам-ботов, Вам необходимо включить Javascript для его просмотра.
&key=c47662ba2504508bcdd5cb75106110a6
01 |
include ( 'database_connection.php' ); |
02 |
if (isset( $_POST [ 'formsubmitted' ])) { |
03 |
$error = array (); //Declare An Array to store any error message |
04 |
if ( empty ( $_POST [ 'name' ])) { //if no name has been supplied |
05 |
$error [] = 'Please Enter a name ' ; //add to array "error" |
07 |
$name = $_POST [ 'name' ]; //else assign it a variable |
10 |
if ( empty ( $_POST [ 'e-mail' ])) { |
11 |
$error [] = 'Please Enter your Email ' ; |
14 |
if (preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , |
16 |
//regular expression for email validation |
17 |
$Email = $_POST [ 'e-mail' ]; |
19 |
$error [] = 'Your EMail Address is invalid ' ; |
24 |
if ( empty ( $_POST [ 'Password' ])) { |
25 |
$error [] = 'Please Enter Your Password ' ; |
27 |
$Password = $_POST [ 'Password' ]; |
30 |
if ( empty ( $error )) //send to Database if there's no error ' |
32 |
{ // If everything's OK... |
34 |
// Make sure the email address is available: |
35 |
$query_verify_email = "SELECT * FROM members WHERE Email ='$Email'" ; |
36 |
$result_verify_email = mysqli_query( $dbc , $query_verify_email ); |
37 |
if (! $result_verify_email ) { //if the Query Failed ,similar to if($result_verify_email==false) |
38 |
echo ' Database Error Occured ' ; |
41 |
if (mysqli_num_rows( $result_verify_email ) == 0) { // IF no previous user is using this email . |
43 |
// Create a unique activation code: |
44 |
$activation = md5(uniqid(rand(), true)); |
47 |
"INSERT INTO `members` ( `Username`, `Email`, `Password`, `Activation`) VALUES ( '$name', '$Email', '$Password', '$activation')" ; |
49 |
$result_insert_user = mysqli_query( $dbc , $query_insert_user ); |
50 |
if (! $result_insert_user ) { |
54 |
if (mysqli_affected_rows( $dbc ) == 1) { //If the Insert Query was successfull. |
57 |
$message = " To activate your account, please click on this link:\n\n" ; |
58 |
$message .= WEBSITE_URL . '/activate.php?email=' . urlencode( $Email ) . "&key=$activation" ; |
59 |
mail( $Email , 'Registration Confirmation' , $message , 'From:' .EMAIL); |
61 |
// Flush the buffered output. |
64 |
echo '<div class = "success" >Thank you for |
65 |
registering! A confirmation email |
66 |
has been sent to ' . $Email . |
67 |
' Please click on the Activation Link to Activate your account </div>' ; |
69 |
} else { // If it did not run OK. |
70 |
echo '<div class = "errormsgbox" >You could not be registered due to a system |
71 |
error. We apologize for any |
72 |
inconvenience.</div>'; |
75 |
} else { // The email address is not available. |
76 |
echo '<div class = "errormsgbox" >That email |
77 |
address has already been registered. |
81 |
} else { //If the "error" array contains error msg , display them |
84 |
foreach ( $error as $key => $values ) { |
86 |
echo ' <li>' . $values . '</li>' ; |
93 |
mysqli_close( $dbc ); //Close the DB Connection |
95 |
} // End of the main Submit conditional. |
Step 4 : Activation Page
This Page contains code that will activate the new member’s account. This will verify the Activation key in the Activation url against the key in the Database, if there is a match, the Database field “Activation” is set to NULL. .A Message informing the user that his or her account has been created successfully.
01 |
include ( 'database_connection.php' ); |
02 |
if (isset( $_GET [ 'email' ]) && preg_match( '/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/' , |
04 |
$email = $_GET [ 'email' ]; |
06 |
if (isset( $_GET [ 'key' ]) && ( strlen ( $_GET [ 'key' ]) == 32)) |
07 |
//The Activation key will always be 32 since it is MD5 Hash |
12 |
if (isset( $email ) && isset( $key )) { |
14 |
// Update the database to set the "activation" field to null |
16 |
$query_activate_account = "UPDATE members SET Activation=NULL WHERE(Email ='$email' AND Activation='$key')LIMIT 1" ; |
17 |
$result_activate_account = mysqli_query( $dbc , $query_activate_account ); |
19 |
// Print a customized message: |
20 |
if (mysqli_affected_rows( $dbc ) == 1) //if update query was successfull |
22 |
echo '<div>Your account is now active. You may now <a href="/login.php">Log in</a></div>' ; |
25 |
echo '<div>Oops !Your account could not be activated. Please recheck the link or contact the system administrator.</div>' ; |
32 |
echo '<div>Error Occured .</div>' ; |
Step 4 :Login Page
The Code below handle the Login form. If there is a match record in the database, a session is created and the member is redirected to page.php .
01 |
< form action = "login.php" method = "post" > |
03 |
< legend >Login Form </ legend > |
05 |
< p >Enter Your username and Password Below </ p > |
08 |
< label for = "name" >Email :</ label > |
09 |
< input type = "text" id = "e-mail" name = "e-mail" size = "25" /> |
13 |
< label for = "Password" >Password:</ label > |
14 |
< input type = "password" id = "Password" name = "Password" size = "25" /> |
17 |
< input type = "hidden" name = "formsubmitted" value = "TRUE" /> |
18 |
< input type = "submit" value = "Login" /> |
PHP Code to Handle the Login Form Submission
The code below contains basic validation as follows :
- Check if both field is empty.
- Check if email is in correct format using regular expression.
01 |
include ( 'database_connection.php' ); |
02 |
if (isset( $_POST [ 'formsubmitted' ])) { |
03 |
// Initialize a session: |
05 |
$error = array (); //this aaray will store all error messages |
07 |
if ( empty ( $_POST [ 'e-mail' ])) { //if the email supplied is empty |
08 |
$error [] = 'You forgot to enter your Email ' ; |
11 |
if (preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $_POST [ 'e-mail' ])) { |
12 |
$Email = $_POST [ 'e-mail' ]; |
14 |
$error [] = 'Your EMail Address is invalid ' ; |
18 |
if ( empty ( $_POST [ 'Password' ])) { |
19 |
$error [] = 'Please Enter Your Password ' ; |
21 |
$Password = $_POST [ 'Password' ]; |
24 |
if ( empty ( $error )) //if the array is empty , it means no error found |
26 |
$query_check_credentials = "SELECT * FROM members WHERE (Email='$Email' AND password='$Password') AND Activation IS NULL" ; |
27 |
$result_check_credentials = mysqli_query( $dbc , $query_check_credentials ); |
28 |
if (! $result_check_credentials ){ //If the QUery Failed |
32 |
if (@mysqli_num_rows( $result_check_credentials ) == 1) //if Query is successfull |
33 |
{ // A match was made. |
35 |
$_SESSION = mysqli_fetch_array( $result_check_credentials , MYSQLI_ASSOC); |
37 |
//Assign the result of this query to SESSION Global Variable |
39 |
header( "Location: page.php" ); |
42 |
{ $msg_error = 'Either Your Account is inactive or Email address /Password is Incorrect' ; |
46 |
foreach ( $error as $key => $values ) { |
47 |
echo ' <li>' . $values . '</li>' ; |
51 |
if (isset( $msg_error )){ |
52 |
echo '<div>' . $msg_error . ' </div>' ; |
56 |
} // End of the main Submit conditional. |
Step 5 : Member Section Page
After Login successfully ,The new member will be redirected to page.php .
3 |
if (!isset( $_SESSION [ 'Username' ])){ |
4 |
header( "Location: login.php" ); |
8 |
<div class = "success" >Welcome , $_SESSION [ 'Username' ]</div> |
You can download the complete source code below . Please make the appropriate changes in the database_connection.php file .
http://youhack.me/2010/04/01/building-a-registration-system-with-email-verification-in-php/
|