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.
<?php
/*Define constant to connect to database */
DEFINE('DATABASE_USER', 'root');
DEFINE('DATABASE_PASSWORD', '');
DEFINE('DATABASE_HOST', 'localhost');
DEFINE('DATABASE_NAME', 'forum');
/*Default time zone ,to be able to send mail */
date_default_timezone_set('UTC');
/*You might not need this */
ini_set('SMTP', "mail.myt.mu");
// Overide The Default Php.ini settings for sending mail
//This is the address that will appear coming from ( Sender )
define('EMAIL', 'email@gmail.com');
/*Define the root url where the script will be found such as
http://website.com or http://website.com/Folder/ */
DEFINE('WEBSITE_URL', 'http://localhost');
// Make the connection:
$dbc = @mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
DATABASE_NAME);
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
?>
Database Structure

-- -- Table structure for table `members` -- CREATE TABLE IF NOT EXISTS `members` ( `Memberid` int(10) NOT NULL AUTO_INCREMENT, `Username` varchar(20) NOT NULL, `Email` varchar(20) NOT NULL, `Password` varchar(10) NOT NULL, `Activation` varchar(40) DEFAULT NULL, PRIMARY KEY (`Memberid`) ) 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 .
<form action="index.php" method="post" class="registration_form">
<fieldset>
<legend>Registration Form </legend>
<p>Create A new Account <span style="background:#EAEAEA none repeat scroll 0 0;line-height:1;margin-left:210px;;padding:5px 7px;">
Already a member? <a href="login.php">Log in</a></span> </p>
<div class="elements">
<label for="name">Name :</label>
<input type="text" id="name" name="name" size="25" />
</div>
<div class="elements">
<label for="e-mail">E-mail :</label>
<input type="text" id="e-mail" name="e-mail" size="25" />
</div>
<div class="elements">
<label for="Password">Password:</label>
<input type="password" id="Password" name="Password" size="25" />
</div>
<div class="submit">
<input type="hidden" name="formsubmitted" value="TRUE" />
<input type="submit" value="Register" />
</div>
</fieldset>
</form>
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=admin@example.com&key=c47662ba2504508bcdd5cb75106110a6
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array(); //Declare An Array to store any error message
if (empty($_POST['name'])) { //if no name has been supplied
$error[] = 'Please Enter a name '; //add to array "error"
} else {
$name = $_POST['name']; //else assign it a variable
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",
$_POST['e-mail'])) {
//regular expression for email validation
$Email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['Password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['Password'];
}
if (empty($error)) //send to Database if there's no error '
{ // If everything's OK...
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM members WHERE Email ='$Email'";
$result_verify_email = mysqli_query($dbc, $query_verify_email);
if (!$result_verify_email) { //if the Query Failed ,similar to if($result_verify_email==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$query_insert_user =
"INSERT INTO `members` ( `Username`, `Email`, `Password`, `Activation`) VALUES ( '$name', '$Email', '$Password', '$activation')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " To activate your account, please click on this link:\n\n";
$message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation";
mail($Email, 'Registration Confirmation', $message, 'From:'.EMAIL);
// Flush the buffered output.
// Finish the page:
echo '<div class="success">Thank you for
registering! A confirmation email
has been sent to ' . $Email .
' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system
error. We apologize for any
inconvenience.</div>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email
address has already been registered.
</div>';
}
} else { //If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>' . $values . '</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc); //Close the DB Connection
} // 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.
include ('database_connection.php');
if (isset($_GET['email']) && preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/',
$_GET['email'])) {
$email = $_GET['email'];
}
if (isset($_GET['key']) && (strlen($_GET['key']) == 32))
//The Activation key will always be 32 since it is MD5 Hash
{
$key = $_GET['key'];
}
if (isset($email) && isset($key)) {
// Update the database to set the "activation" field to null
$query_activate_account = "UPDATE members SET Activation=NULL WHERE(Email ='$email' AND Activation='$key')LIMIT 1";
$result_activate_account = mysqli_query($dbc, $query_activate_account);
// Print a customized message:
if (mysqli_affected_rows($dbc) == 1) //if update query was successfull
{
echo '<div>Your account is now active. You may now <a href="login.php">Log in</a></div>';
} else {
echo '<div>Oops !Your account could not be activated. Please recheck the link or contact the system administrator.</div>';
}
mysqli_close($dbc);
} else {
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 .
<form action="login.php" method="post"> <fieldset> <legend>Login Form </legend> <p>Enter Your username and Password Below </p> <div> <label for="name">Email :</label> <input type="text" id="e-mail" name="e-mail" size="25" /> </div> <div> <label for="Password">Password:</label> <input type="password" id="Password" name="Password" size="25" /> </div> <div> <input type="hidden" name="formsubmitted" value="TRUE" /> <input type="submit" value="Login" /> </div> </fieldset> </form>
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.
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
// Initialize a session:
session_start();
$error = array();//this aaray will store all error messages
if (empty($_POST['e-mail'])) {//if the email supplied is empty
$error[] = 'You forgot to enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) {
$Email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['Password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['Password'];
}
if (empty($error))//if the array is empty , it means no error found
{
$query_check_credentials = "SELECT * FROM members WHERE (Email='$Email' AND password='$Password') AND Activation IS NULL";
$result_check_credentials = mysqli_query($dbc, $query_check_credentials);
if(!$result_check_credentials){//If the QUery Failed
echo 'Query Failed ';
}
if (@mysqli_num_rows($result_check_credentials) == 1)//if Query is successfull
{ // A match was made.
$_SESSION = mysqli_fetch_array($result_check_credentials, MYSQLI_ASSOC);
//Assign the result of this query to SESSION Global Variable
header("Location: page.php");
}else
{ $msg_error= 'Either Your Account is inactive or Email address /Password is Incorrect';
}
} else {
echo '<div> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
if(isset($msg_error)){
echo '<div>'.$msg_error.' </div>';
}
/// var_dump($error);
mysqli_close($dbc);
} // End of the main Submit conditional.
Step 5 : Member Section Page
After Login successfully ,The new member will be redirected to page.php .
ob_start();
session_start();
if(!isset($_SESSION['Username'])){
header("Location: login.php");
}
?>
<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 .






{ 1 trackback }
{ 89 comments… read them below or add one }
← Previous Comments
thanks for the good work
@Li & @Hyder
Im getting the same error. imean to say i get everything correct till getting the verification link…
But the link has “%40″ instead of the “@” sign in emailid part also i tried manually editing that in the address bar and it shows “ACCOUNT SUCCESSFULLY VERIFIED. PLEASE LOGIN” but wen i try to login it shows “Email eith Inactive or has not been verified”
Also m executing the script on a subdomain of my website, so in the verification link i get “localhost” instead of the website URL part at the begining of the verification link
Please help i m in urgent need of this script..
N hyder bro u r gr8!! Thanx a ton to you man!! You Rock!
try to verify the database password varchart and modify it from 10 to 40
And how will this be code MySQL
$query_verify_email = “SELECT * FROM members WHERE Email =’$Email’”;
$result_verify_email = mysqli_query($dbc, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
echo ‘ Database Error Occured ‘;
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$query_insert_user = “INSERT INTO `members` ( `Username`, `Email`, `Password`, `Activation`) VALUES ( ‘$name’, ‘$Email’, ‘$Password’, ‘$activation’)”;
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo ‘Query Failed ‘;
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = ” To activate your account, please click on this link:\n\n”;
$message .= WEBSITE_URL . ‘/activate.php?email=’ . urlencode($Email) . “&key=$activation”;
mail($Email, ‘Registration Confirmation’, $message, ‘From: ismaakeel@gmail.com‘);
Hi,
I’ve 2 problems with the codes:(
Firstly, whenever i tried loggin in, theres are these “Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at /home/kusiosg/public_html/login.php:10) in /home/kusiosg/public_html/login.php on line 140″ and “Warning: Cannot modify header information – headers already sent by (output started at /home/kusiosg/public_html/login.php:10) in /home/kusiosg/public_html/login.php on line 189
” showing on top of the login box.
I have tried solving it multiple times but still can’t be solved.
Another problem is that i have already changed the email to my own email as well as changed the SMTP (i do have the hosting service), however the sender mail is still default(ismaakeel@gmail.com).
Please reply asap:(
thanks in advance!
Oh, i have solved the second problem!:) please help me with the first problem! thanks!:D
what will be the code if a unregister user is trying to see the page and i want to rediect him to loging page can u plz help me
and ya i have made a logout page as it was show in comment plzz help me as soon as u can i will be waiting for ur reaply
Superb tutorial.
I was tempted to enter an irregular email address while writing this post- but then I decided otherwise :)
Thanks for the post.
im still not getting any email confirmation to activate my account.. why do you is the problem? Please help me.. Im stuck…
Hi, i am not geting email confirmation from your script. First time it come but second no!
Mantabz..!! from Indonesia..
i get this…sombody plz help….
Warning: mail() [function.mail]: Failed to connect to mailserver at “mail.myt.mu” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in C:\xampp\htdocs\Myfirstwebsite\index.php on line 69
hello, i think you can find some help here
http://www.apachefriends.org/f/viewtopic.php?f=4&t=41901
have a nice day
Hello Hyder,
I am able to install your code successfully on my web server. Also I have successfully edited my SMTP server address (as provided by my host) in the config file but still i am unable to get the confirmation email. I have also tried deleting that SMTP code line as well as changing it to POP3 & IMAP but nothing seems to work uptil now. Rest everything is working absolutely fine!
Also is there any way to contact you for my project? I have a similar project in which I would like to get your help. Please reply at your earliest as I am really in need of a great programmer like you. Thank you!
Hello Hyder
am getting this error
( ! ) Warning: mail() [function.mail]: SMTP server response: 550 Access denied – Invalid HELO name (See RFC2821 4.1.1.1) in C:\wamp\www\index.php on line 69
please help me
hi hyder
i wanna ask that how to avoid same username!!!
Hey, can someone help me with a problem. When I get the activation mail, the sender is the one who posted this code. I wanna change it to my own emailaddress. And another thing, after activating, it gives me the error code. Can someone help me with that?
Warning: mail() [function.mail]: Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in C:\xampp\htdocs\php_reg\index.php on line 69
i got error like that … but database has been updated… kindly suggest me any solution please…
i think you need to unlok your port 25 SMTP, it is a email problem, as i see u are using xampp, try and use a real webserver FTP
here , i think you can find some help
http://www.apachefriends.org/f/viewtopic.php?f=4&t=41901
have a nice day
how to change %40 to @?
it’s very hard to see and what will change
please help me bro..
Hello Hyder, please can someone tell me f i want the form also emailed with the activation link how can i do that?
So the email will show the activation link + info from the form such as , email, name and so on.
Thank you :)
i rezolved this, thank you
Thx for the script easy to get it working.
Maybe its its a good idea to also have a simple anti-spam form integrated in the activation page.
← Previous Comments