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 }
{ 137 comments… read them below or add one }
← Previous Comments
IM USING THIS CODE TO LOCAL HOST ITS SHOWING SOME ERROR HOW AM SOLVE
ERROR:
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\vvv\sample\index.php on line 73
hi siir i have an error iin index.php (activation page)
line no 58 and 59 (where i put my link )
Hi Guys,
I got this error when i using this code into my domain. can u guys help me out how can i resolve this problem. waiting for any one’s advise
Oops !Your account could not be activated. Please recheck the link or contact the system administrator.
Thanks!
hello its very helpfull for me thanks… i want updated database can u send it ? .
i am gettting this error help me
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 G:\wamp\www\New Folder (4)\index.php on line 69
Hey,
I always get an error when trying to register at the register.php file.
Can you help me please ?
Thanks
Please email the answer to dcassiman@gmail.com cause i’m not so many times on this website.
I have been browsing online more than 4 hours today,
yet I never found any interesting article like yours. It is pretty
worth enough for me. Personally, if all webmasters and
bloggers made good content as you did, the web
will be much more useful than ever before.
hi why i run your code always error
“Oops !Your account could not be activated. Please recheck the link or contact the system administrator.”
please tell me…
hello,
please i need your correction here, once the email is sent correctly, the success message that appears does not show title, name and the email on the screen but other messages are being displayed. please how can i get the screen to show these details before the messages.
// Finish the page:
echo ‘Thank’ $title $name ‘you for
registering! A confirmation email has been sent to’ . $Email .
‘ Please click on the Activation Link to Activate your account ‘;
hi this is the second time i am posting but have not got any reply. i have included sql injection control in the code, not working if i use it. but working without the mysql_real_escape_string. please can you help below is my code
if (empty($_POST['firstname'])) { //if no name has been supplied
$error[] = ‘Please Enter a first name ‘; //add to array “error”
} else {
$firstname = mysql_real_escape_string( stripslashes( $_POST[ 'firstname' ] ) ); //else assign it a variable
Very nice article. It really helped me a lot.
← Previous Comments