PHP Email Verification Script.
Wall Script
Follow Me:
Tuesday, November 12, 2013

PHP Email Verification Script.

I received lots tutorial requests from my readers in that most of them asked to me, how to implement email verification system using PHP. This is very basic tutorial explained how to create database and proper activation code. Implemented with mysqli_() fuctions, because mysql_() functions are depreciated.

PHP Email Verification Script.


Download Script     Live Demo

Database
Sample database users table contains four columns uid, email, password, activation and status.
CREATE TABLE IF NOT EXISTS `users` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(300) NOT NULL UNIQUE,
`password` varchar(300) NOT NULL,
`activation` varchar(300) NOT NULL UNIQUE,
`status` enum('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (`uid`)
)

HTML Code
Contains simple HTMl code.
<form action="" method="post">
<label>Email</label>
<input type="text" name="email" class="input" autocomplete="off"/>
<label>Password </label>
<input type="password" name="password" class="input" autocomplete="off"/><br/>
<input type="submit" class="button" value="Registration" />
<span class='msg'><?php echo $msg; ?></span>
</form>

db.php
Database configuration file, modify username, password, database and base url values.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = @mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
$base_url='http://www.youwebsite.com/email_activation/';
?>

index.php
Contains PHP code, storing user registration values into users table. Here activation code generation using MD5 encryption.
<?php
include 'db.php';
$msg='';
if(!empty($_POST['email']) && isset($_POST['email']) &&  !empty($_POST['password']) &&  isset($_POST['password']) )
{
// username and password sent from form
$email=mysqli_real_escape_string($connection,$_POST['email']);
$password=mysqli_real_escape_string($connection,$_POST['password']);
// regular expression for email check
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/';

if(preg_match($regex, $email))
{
$password=md5($password); // encrypted password
$activation=md5($email.time()); // encrypted email+timestamp
$count=mysqli_query($connection,"SELECT uid FROM users WHERE email='$email'");
// email check
if(mysqli_num_rows($count) < 1)
{
mysqli_query($connection,"INSERT INTO users(email,password,activation) VALUES('$email','$password','$activation')");
// sending email
include 'smtp/Send_Mail.php';
$to=$email;
$subject="Email verification";
$body='Hi, <br/> <br/> We need to make sure you are human. Please verify your email and get started using your Website account. <br/> <br/> <a href="'.$base_url.'activation/'.$activation.'">'.$base_url.'activation/'.$activation.'</a>';

Send_Mail($to,$subject,$body);
$msg= "Registration successful, please activate email.";
}
else
{
$msg= 'The email is already taken, please try new.';
}

}
else
{
$msg = 'The email you have entered is invalid, please try again.';
}

}
// HTML Part
?>

Send_Mail.php
Sending email function, just modify SMTP host, username and password. Here you can use GMail SMTP details for testing click here to see GMail SMTP article.
<?php
function Send_Mail($to,$subject,$body)
{
require 'class.phpmailer.php';
$from       = "from@yourwebsite.com";
$mail       = new PHPMailer();
$mail->IsSMTP(true);            // use SMTP
$mail->IsHTML(true);
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Host       = "tls://smtp.yourwebsite.com"; // SMTP host
$mail->Port       =  465;                    // set the SMTP port
$mail->Username   = "SMTP_Username";  // SMTP  username
$mail->Password   = "SMTP_Password";  // SMTP password
$mail->SetFrom($from, 'From Name');
$mail->AddReplyTo($from,'From Name');
$mail->Subject    = $subject;
$mail->MsgHTML($body);
$address = $to;
$mail->AddAddress($address, $to);
$mail->Send();
}
?>

activation.php
Contains PHP code, here based on activations code user status updating from 0 to 1.
<?php
include 'db.php';
$msg='';
if(!empty($_GET['code']) && isset($_GET['code']))
{
$code=mysqli_real_escape_string($connection,$_GET['code']);
$c=mysqli_query($connection,"SELECT uid FROM users WHERE activation='$code'");

if(mysqli_num_rows($c) > 0)
{
$count=mysqli_query($connection,"SELECT uid FROM users WHERE activation='$code' and status='0'");

if(mysqli_num_rows($count) == 1)
{
mysqli_query($connection,"UPDATE users SET status='1' WHERE activation='$code'");
$msg="Your account is activated";
}
else
{
$msg ="Your account is already active, no need to activate again";
}

}
else
{
$msg ="Wrong activation code.";
}

}
?>
//HTML Part
<?php echo $msg; ?>

Email Verification
PHP Email Verification Script.

.htaccess
URL redirection script it turns
http://website.com/activation.php?code=ACTIVATION_CODE
to
http://website.com/activation/ACTIVATION_CODE
RewriteEngine On

RewriteRule ^activation/([a-zA-Z0-9_-]+)$ activation.php?code=$1
RewriteRule ^activation/([a-zA-Z0-9_-]+)/$ activation.php?code=$1

CSS code
body
{
font-family: "Helvetica",Arial,sans-serif;
font-weight: 500;
color:#333;
}
label
{
width:100px;
display:block;
font-weight:bold;
color:#666666;
}
#main
{
margin:0 auto;
width:800px;
}
.input
{
padding:10px;
font-size:14px;
border:1px solid #999999;
width:200px;
margin-bottom:10px;
}
.button {
padding:10px;
background-color: #5fcf80 !important;
border-color: #3ac162 !important;
}
.msg
{
font-size:11px;
color:#666;
padding:10px;
}
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


97 comments:

  1. f-yah ive been waiting for this.
    thank you so much..canyou please make one for admin area? where admin can de-activate the users account?

    ReplyDelete
  2. That's a nice tutorial, thanks for the email.

    ReplyDelete
  3. Why use you the google comment system?
    This afful!
    Otherwise, thanks for the tutorial, but how can I implemet to wordpress?

    ReplyDelete
  4. nice tutorial.. I was creating similar tutorial and just saw you published. I liked that url redirection part.

    ReplyDelete
  5. Simple And Nice Tutorial. Looking for more.

    ReplyDelete
  6. why use URL redirection script it turns

    ReplyDelete
  7. hello

    hey ! Yes it's useful
    it can be use to validate classifieds ads or commenting system

    thanks

    ReplyDelete
  8. Hi there,
    If mysql_() functions are deprictaed, is it good to use mysql_real_escape_string() ? Is there another function which is better than mysql_real_escape_string() to escape quoted values?

    ReplyDelete
  9. M getting this error


    Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'feelcomf'@'localhost' (using password: NO) in /home/feelcomf/public_html/sadhvigroups.com/demo/emailconfirmation/index.php on line 8

    ReplyDelete
  10. Hi, nice script! But why did you use "mysql_real_escape_string" and there a mysqli function for?

    ReplyDelete
  11. only srinivas tamada can do like this!! awesome hatsoff @srinivastamada

    ReplyDelete
  12. Basic step in user registration system came so late for an advanced site..weird!...Useful for a newbie though

    ReplyDelete
  13. Hi friend.,
    Here my small suggestion is, have a small bug in that kindly change if you are going to use this code

    in INDEX.PHP

    // email check
    if(mysqli_num_rows($count) < 1)// the number of rows should be == 1 or >0
    {
    mysqli_query($connection,"INSERT INTO users(email,password,activation) VALUES('$email','$password','$activation')");
    // sending email

    ReplyDelete
  14. Hi. its a great stuff but there are two things that can be done.
    on latest version of PHP we can use
    var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)); instead of regular expression

    also and additional check to see if the user is already registered or have registered but the verification is pending and on the basis of that we can send mail.

    Keep rocking.
    www,thesoftwareguy.in

    ReplyDelete
  15. Thanks for the detailed script

    ReplyDelete
  16. you are great and thanks a lot for such posts

    today i sent mail from local_host using gmail_smtp on window platform .



    ReplyDelete
  17. Nice Site ...very useful Tutorial....

    ReplyDelete
  18. Thanks Srinivas, I was in search of this code. Your tutorials are very useful and very easy to implement.

    Thanks again for such beautiful code of email verification.

    ReplyDelete
  19. I'm a big fan of your blog... keep the tutorials coming! thanks.

    ReplyDelete
  20. Great article…I have read many topics here all are very good…

    ReplyDelete
  21. need help 'http://www.youwebsite.com/email_activation/'; want to know where is email_activation.php file new to developing bare with me thanks

    ReplyDelete
  22. can anyone tell me what is "class.phpmailer.php" and where can i found it???????

    ReplyDelete
  23. SUDDENLY MY SMTP EMAIL VERIFCATION STOPED SENDING EMAILS,,,,, NO RESPONSE

    ReplyDelete
  24. awsome site.. very helpful..

    ReplyDelete
  25. what to change in send.php to make it working,,

    ReplyDelete
  26. How about keeping activation code in users sessions?

    ReplyDelete
  27. Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\email_activation\index.php on line 17

    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\email_activation\index.php on line 18

    Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\email_activation\index.php on line 20

    plz help to resolve these warnings

    ReplyDelete
  28. this tutorial helps me a lot ..
    thanks bro ...
    u r my teacher ...

    ReplyDelete
  29. Hi can you please help me:

    where should i write this code, I mean in which file, the code:

    RewriteEngine On

    RewriteRule ^activation/([a-zA-Z0-9_-]+)$ activation.php?code=$1
    RewriteRule ^activation/([a-zA-Z0-9_-]+)/$ activation.php?code=$1

    plz reply me. waiting for your reply.............

    bilalbinamar@rediff.com

    let me know when u reply On bilalbinamar@rediff.com

    ReplyDelete
  30. Shivrajan Singh: you can fine the class.phpmailler.php

    from this link just copy it and save in the same location with the other file or see the location the other file

    here is the link for class.phpmailer.php

    https://code.google.com/a/apache-extras.org/p/phpmailer/source/browse/trunk/class.phpmailer.php

    you will also need class.smtp.php and link is here:

    https://code.google.com/a/apache-extras.org/p/phpmailer/source/browse/trunk/class.smtp.php?r=7

    ReplyDelete
  31. Hi,
    Can anyone help me with how to resolve this error?

    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\Backstretch\emailauthIndex.php on line 24

    Also, the code works really well, except data from the form does not seem to be getting to my database and I have no idea why...everything else works okay, email with activation code is sent but I can keep signing up with the same email address and the system won't know.

    Please help!
    Thanks.

    ReplyDelete
  32. Hi everyone,

    the script is written very well manner, easy to understand. I am getting problems during the execution of this script.
    1) When i am clicking on activation link to activate an account, it's showing that URL /activation/74bedce29eab40e1572bda5beb922386 was not found on this server.
    2) I am not getting the $_GET['code'], from where the input variable code came, in activation.php file. if its from activation link, please guide me how to get activation link to activation.php files.

    email-id: aaryaok@gmail.com

    Thanks in advance

    ReplyDelete
  33. Hi,

    after clicking on activation link i am getting this error:

    ****************
    Not Found
    ****************
    The requested URL /emailsmtp/includes/f727ac95140514b002f625885f63b258 was not found on this server.

    Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

    ********************************************************************************************
    .htaccess file is placed at same location with activation.php and index.php files:
    ********************************************************************************************
    RewriteEngine On

    RewriteRule ^emailsmtp/includes/([a-zA-Z0-9_-]+)$ activation.php?code=$1
    RewriteRule ^emailsmtp/includes/([a-zA-Z0-9_-]+)/$ activation.php?code=$1

    please guide me.
    email-id: aaryaok@gmail.com

    ReplyDelete
  34. Hi,

    I used this code to send email to the clients. The HTML tags is working in Gmail but not in Yahoo and other Mail Servers.

    Please help.
    Thanks.

    ReplyDelete
  35. Error: Parse error: syntax error, unexpected end of file in /home/XXXXXXXXXX/public_html/gmail/smtp/class.phpmailer.php on line 811

    ReplyDelete
  36. where is class.phpmailer.php file ????????

    ReplyDelete
  37. hi sir

    how can i create in html send verification mail for activation of ad that i want to post or submit in my site.

    i want to ad category place ad and when someone submit ad then a verification mail should go to his email and then click verification mail after ad active

    please help me

    waiting for your reply

    ReplyDelete
  38. that email can working in offline mode or must online mode?thank you.

    ReplyDelete
  39. MySQL has not been deprecated. It is being thought if it has to be or not.

    ReplyDelete
  40. is it work in localhost???
    it is giving me error to inport db
    in mylocalhost
    tell its solution

    ReplyDelete
  41. it will not work on localhost you have to upload your content on server.. and admin nyc tutorial but can you please make tutorial for getting forgot password retrieval with email...?

    ReplyDelete
  42. nice work! could you tell me how to integrate it with prestashop1.6

    ReplyDelete
  43. All the topic posted here is so useful for freshers like me . Thanks

    ReplyDelete
  44. I have no idea how to trigger the form, i'm using an external index.html, even your action="", how do they really trigger??

    ReplyDelete
  45. mail was not sent only insert into data base please help

    ReplyDelete
  46. Your post is really helpful for me. Thanks for your wonderful post. It is really very helpful for us and I have gathered some important information from this blog.

    ReplyDelete
  47. gooooooooodddddddddd jobbbbbbbbbbbbbbbb

    ReplyDelete
  48. mail was not sent only insert into data base please help.

    ReplyDelete
  49. That's very useful for me..but i need one help..how to check the email id is already exists or not using php please help me..

    ReplyDelete
  50. where to put the code of activation link and to create activation link.
    RewriteEngine On

    RewriteRule ^activation/([a-zA-Z0-9_-]+)$ activation.php?code=$1
    RewriteRule ^activation/([a-zA-Z0-9_-]+)/$ activation.php?code=$1

    ReplyDelete
  51. email verification/activation link not going to mail.how to send link.

    ReplyDelete
  52. I m looking for something like that
    a mail drop to his mail and user verify this email by cliking on this...

    ReplyDelete
  53. Note: Little problem with my SMTP server, emails are not working. I am working on this issue.

    ReplyDelete
  54. i got Registration successful, please activate email. but mail did not receive..

    any problem??? plz help me brother!!!

    ReplyDelete
  55. Your code doesnt work.. You should use send_mail (); to call the function in index.php

    ReplyDelete
  56. hi,may i know how to fix these warnings..
    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\email_activation\index.php on line 7

    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\email_activation\index.php on line 8

    ReplyDelete
  57. after click on link in mail its showing page not found

    ReplyDelete
  58. Hi i was wondering if this script can be used for mssql. Do i need to replace mssqli?newbie thanks

    ReplyDelete
  59. I am not recieving any verification and your live demo is also not working.

    ReplyDelete
  60. I CANT :(
    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\a14\email_activation2\index.php on line 7

    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\a14\email_activation2\index.php on line 8

    what must I do?

    ReplyDelete
    Replies
    1. Include connection mysqli_real_escape_string($connection, $value);

      Delete
  61. This will not work for me can you please create a code for woocommerce enquiry form in which user enter their email address and it will first verificate and the send email to admin for order.

    ReplyDelete
  62. hi
    I am getting this error

    PHP Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli

    Please help me with this

    ReplyDelete
  63. can u please tell me .htaccess file and do i need to type .htaccess code or is it builtin??

    ReplyDelete

Make in India