Tutorial Details
- Technology: PHP
- Difficulty: Intermediate
- Completion Time: 1-2 hours
Have you ever created an account with a website, and were required to check your email and click through a verification link sent by the company in order to activate it? Doing so highly reduces the number of spam accounts. In this lesson, we’ll learn how to do this very thing!
What Are We Going to Build?
We are going to build a nice PHP sign-up script where a user can create an account to gain access to a “members section” of a website.
After the user creates his account, the account will then be locked until the user clicks a verification link that he will receive in his email inbox.
Step 1 - Sign-up Page
We first need a simple page where our visitors can sign up their accounts; so that’s the first thing we will build.
I would like to remind you that this is a PHP tutorial, and in my opinion, I think you need to know the basics of HTML before moving on with PHP. I’ll add comments to the HTML & CSS to describe each line of code.
index.php – This is our sign up page with a basic form.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>NETTUTS > Sign up</title> <link href="css/style.css" type="text/css" rel="stylesheet" /> </head> <body> <!-- start header div --> <div id="header"> <h3>NETTUTS > Sign up</h3> </div> <!-- end header div --> <!-- start wrap div --> <div id="wrap"> <!-- start php code --> <!-- stop php code --> <!-- title and description --> <h3>Signup Form</h3> <p>Please enter your name and email addres to create your account</p> <!-- start sign up form --> <form action="" method="post"> <label for="name">Name:</label> <input type="text" name="name" value="" /> <label for="email">Email:</label> <input type="text" name="email" value="" /> <input type="submit" class="submit_button" value="Sign up" /> </form> <!-- end sign up form --> </div> <!-- end wrap div --> </body> </html>
css/style.css – This is stylesheet for index.php and further pages.
/* Global Styles */
*{
padding: 0; /* Reset all padding to 0 */
margin: 0; /* Reset all margin to 0 */
}
body{
background: #F9F9F9; /* Set HTML background color */
font: 14px "Lucida Grande"; /* Set global font size & family */
color: #464646; /* Set global text color */
}
p{
margin: 10px 0px 10px 0px; /* Add some padding to the top and bottom of the <p> tags */
}
/* Header */
#header{
height: 45px; /* Set header height */
background: #464646; /* Set header background color */
}
#header h3{
color: #FFFFF3; /* Set header heading(top left title ) color */
padding: 10px; /* Set padding, to center it within the header */
font-weight: normal; /* Set font weight to normal, default it was set to bold */
}
/* Wrap */
#wrap{
background: #FFFFFF; /* Set content background to white */
width: 615px; /* Set the width of our content area */
margin: 0 auto; /* Center our content in our browser */
margin-top: 50px; /* Margin top to make some space between the header and the content */
padding: 10px; /* Padding to make some more space for our text */
border: 1px solid #DFDFDF; /* Small border for the finishing touch */
text-align: center; /* Center our content text */
}
#wrap h3{
font: italic 22px Georgia; /* Set font for our heading 2 that will be displayed in our wrap */
}
/* Form & Input field styles */
form{
margin-top: 10px; /* Make some more distance away from the description text */
}
form .submit_button{
background: #F9F9F9; /* Set button background */
border: 1px solid #DFDFDF; /* Small border around our submit button */
padding: 8px; /* Add some more space around our button text */
}
input{
font: normal 16px Georgia; /* Set font for our input fields */
border: 1px solid #DFDFDF; /* Small border around our input field */
padding: 8px; /* Add some more space around our text */
}
As you can see, I have added a comment to each line that describes what they do. Also, you might have noticed the following comment in the index.php file:
<!-- start php code --> <!-- stop php code -->
We are going to write our PHP between these 2 lines!
Step 2 - Input Validation
The first thing we are going to build is a piece of code that’s going to validate the information. Here is a short list detailing what needs to be done.
- If the name field is not empty.
- If the name is not to short.
- If the email field is not empty.
- If the email address is valid xxx@xxx.xxx
So our first step is checking if the form is being submitted, and that the fields are not empty.
<!-- start PHP code -->
<?php
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['email']) && !empty($_POST['email'])){
// Form Submited
}
?>
<!-- stop PHP Code -->
Time for a breakdown! We start of with an IF statement and we are first validating the name field:
if( ){ // If statement is true run code between brackets
}
isset($_POST['name']) // Is the name field being posted; it does not matter whether it's empty or filled.
&& // This is the same as the AND in our statement; it allows you to check multiple statements.
!empty($_POST['name']) // Verify if the field name is not empty
isset($_POST['email']) // Is the email field being posted; it does not matter if it's empty or filled.
&& // This is the same as the AND in our statement; it allows you to check multiple statements.
!empty($_POST['email']) // Verify if the field email is not empty
So if you would submit the form now with empty fields, nothing happens. If you fill in both fields then our script will run the code between the brackets.
Now we are going to create a peace of code that will check if an email address is valid. If it’s not, we will return a error. Also let’s turn our post variables into local variables:
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['email']) && !empty($_POST['email'])){
$name = mysql_escape_string($_POST['name']); // Turn our post into a local variable
$email = mysql_escape_string($_POST['email']); // Turn our post into a local variable
}
We can now reach our data via our local variables. As you can see, I also added a MySQL escape string to prevent MySQL injection when inserting the data into the MySQL database.
“The mysql_real_escape_string() function escapes special characters in a string for use in an SQL statement.”
Regular Expressions
Next up is a small snippet that checks if the email address is valid.
$name = mysql_escape_string($_POST['name']);
$email = mysql_escape_string($_POST['email']);
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
// Return Error - Invalid Email
}else{
// Return Success - Valid Email
}
Please note that I did not personally write this regular expression, it’s a small snippet from php.net.
Basically, it verifies if the email is written in the following format:
xxx@xxx.xxx
Now in the eregi, you can see that it checks if the email contains characters from the alphabet, if it has any numbers, or a phantom dash (_), and of course the basic requirements for an email (email)’@’ and a (dot)’.’ If none of these characters are found, the expression returns “false”. Okay, so now we need to add some basic error messages.
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
// Return Error - Invalid Email
$msg = 'The email you have entered is invalid, please try again.';
}else{
// Return Success - Valid Email
$msg = 'Your account has been made, <br /> please verify it by clicking the activation link that has been send to your email.';
}
As you can see we have made a local variable “$msg”, this allows us to show the error or the success message anywhere on the page.
And we are going to display it between the instruction text and the form.
<!-- title and description -->
<h3>Signup Form</h3>
<p>Please enter your name and email address to create your account</p>
<?php
if(isset($msg)){ // Check if $msg is not empty
echo '<div class="statusmsg">'.$msg.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
<!-- start sign up form -->
Add this to style.css, to style our status message a bit.
#wrap .statusmsg{
font-size: 12px; /* Set message font size */
padding: 3px; /* Some padding to make some more space for our text */
background: #EDEDED; /* Add a background color to our status message */
border: 1px solid #DFDFDF; /* Add a border arround our status message */
}
Step 3 - Creating the Database & Establishing a Connection
Now we need to establish a database connection and create a table to insert the account data. So let’s go to PHPMyAdmin and create a new database with the name registrations and create a user account that has access to that database in order to insert and update data.
Let’s create our users table, with 5 fields:
So now we must enter details for these fields:
For those who don’t want to input this data manually, you can instead run the following SQL code.
CREATE TABLE `users` ( `id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `username` VARCHAR( 32 ) NOT NULL , `password` VARCHAR( 32 ) NOT NULL , `email` TEXT NOT NULL , `hash` VARCHAR( 32 ) NOT NULL , `active` INT( 1 ) NOT NULL DEFAULT '0' ) ENGINE = MYISAM ;
Our database is created, now we need to establish a connection using PHP. We’ll write the following code at the start of our script just below the following line:
<!-- start PHP code --> <?php // Establish database connection
We’ll use the following code to connect to the database server and select the registrations database. (basic MySQL connection)
mysql_connect("localhost", "username", "password") or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db("registrations") or die(mysql_error()); // Select registrations database.
Now that we’ve established a connection to our database, we can move on to the next step and insert the account details.
Step 4 - Insert Account
Now it’s time to enter the submitted account details to our database and generate an activation hash. Write the following code below this line:
// Return Success - Valid Email $msg = 'Your account has been made, <br /> please verify it by clicking the activation link that has been send to your email.';
Activation Hash
In our database we made a field called hash, this hash is a 32 character string of text. We also send this code to the user’s email address. They then can click the link (which contains the hash) and we will verify if it matches up with the one in the database. Let’s create a local variable called $hash and generate a random md5 hash.
$hash = md5( rand(0,1000) ); // Generate random 32 character hash and assign it to a local variable. // Example output: f4552671f8909587cf485ea990207f3b
What did we do? Well we are using the PHP function “rand” to generate a random number between 0 and 1000. Next our MD5 function will turn this number into a 32 character string of text which we will use in our activation email. My choice is to use MD5, because it generates a hash of 32 characters which is secure and, in this case, impossible to crack.
Creating a Random Password
The next thing we need to is to create a random password for our member:
$password = rand(1000,5000); // Generate random number between 1000 and 5000 and assign it to a local variable. // Example output: 4568
Insert the following information into our database using a MySQL query
mysql_query("INSERT INTO users (username, password, email, hash) VALUES(
'". mysql_escape_string($name) ."',
'". mysql_escape_string(md5($password)) ."',
'". mysql_escape_string($email) ."',
'". mysql_escape_string($hash) ."') ") or die(mysql_error());
As you can see, we insert all data with a MySQL escape string around it to prevent any MySQL injection.
You also might notice that the MD5 function changes the random password into a secure hash for protection. Example: if an “evil” person gains access to the database, he can’t read the passwords.
For testing, fill in the form and check if the data is being inserted into our database.
Step 5 - Send the Verification Email
Right after we have inserted the information into our database, we need to send an email to the user with the verification link. So let’s use the PHP “mail” function to do just that.
$to = $email; // Send email to our user $subject = 'Signup | Verification'; // Give the email a subject $message = ' Thanks for signing up! Your account has been created, you can login with the following credentials after you have activated your account by pressing the url below. ------------------------ Username: '.$name.' Password: '.$password.' ------------------------ Please click this link to activate your account: http://www.yourwebsite.com/verify.php?email='.$email.'&hash='.$hash.' '; // Our message above including the link $headers = 'From:noreply@yourwebsite.com' . "\r\n"; // Set from headers mail($to, $subject, $message, $headers); // Send our email
Now let’s brake down the message:
Thanks for signing up! Your account has been created, you can login with the following credentials after you have activated your account by pressing the url below. ------------------------ Username: '.$name.' Password: '.$password.' ------------------------
In the code above we send a short description to our user which contains the username and password — using the local variables we created when the data was posted.
Please click this link to activate your account: http://www.yourwebsite.com/verify.php?email='.$email.'&hash='.$hash.'
In this section of the code, we created a dynamic link. The result of this will look like this:
As you can see, it creates a solid url, which is impossible to guess. This is a very secure way to verify the email address of a user.
Step 6 - Account Activation
As you can see, our url links to verify.php so let’s create that, using the same basic template we used for index.php.
However, remove the form from the template.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>NETTUTS > Sign up</title>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<!-- start header div -->
<div id="header">
<h3>NETTUTS > Sign up</h3>
</div>
<!-- end header div -->
<!-- start wrap div -->
<div id="wrap">
<!-- start PHP code -->
<?php
mysql_connect("localhost", "tutorial", "password") or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db("registrations") or die(mysql_error()); // Select registration database.
?>
<!-- stop PHP Code -->
</div>
<!-- end wrap div -->
</body>
</html>
The first thing we need to do is check if we have our $_GET variables (email & hash)
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){
// Verify data
}else{
// Invalid approach
}
To make things a bit easier, let’s assign our local variables and add some MySQL injection prevention by, once again, using the MySQL escape string.
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){
// Verify data
$email = mysql_escape_string($_GET['email']); // Set email variable
$hash = mysql_escape_string($_GET['hash']); // Set hash variable
}
Next is to check the data from the url against the data in our database using a MySQL query.
$search = mysql_query("SELECT email, hash, active FROM users WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error());
$match = mysql_num_rows($search);
In the code above, we used a MySQL select statement, and checked if the email and hash matched. But beside that, we checked if the status of the account is “inactive”. Finally, we use mysql_num_rows to determine how many matches have been found. So let’s try this out. Simply use a simple echo to return the results.
$search = mysql_query("SELECT email, hash, active FROM users WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error());
$match = mysql_num_rows($search);
echo $match; // Display how many matches have been found -> remove this when done with testing ;)
We have a MATCH! To change the result, simply change the email and you’ll see that the number returned is 0.
We can use our $match variable to either activate the account or return a error when no match has been found.
if($match > 0){
// We have a match, activate the account
}else{
// No match -> invalid url or account has already been activated.
}
In order to activate the account, we must update the active field to 1 using a MySQL query.
// We have a match, activate the account
mysql_query("UPDATE users SET active='1' WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error());
echo '<div class="statusmsg">Your account has been activated, you can now login</div>';
So we use the same search terms for the update as we used in our MySQL select query. We change active to 1 where the email, hash and field active = 0 match up. We also return a message telling the user that his account has been activated. You can add a message like we did here to the “no match” part. So the final code should look similar to:
mysql_connect("localhost", "tutorial", "password") or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db("registrations") or die(mysql_error()); // Select registration database.
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){
// Verify data
$email = mysql_escape_string($_GET['email']); // Set email variable
$hash = mysql_escape_string($_GET['hash']); // Set hash variable
$search = mysql_query("SELECT email, hash, active FROM users WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error());
$match = mysql_num_rows($search);
if($match > 0){
// We have a match, activate the account
mysql_query("UPDATE users SET active='1' WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error());
echo '<div class="statusmsg">Your account has been activated, you can now login</div>';
}else{
// No match -> invalid url or account has already been activated.
echo '<div class="statusmsg">The url is either invalid or you already have activated your account.</div>';
}
}else{
// Invalid approach
echo '<div class="statusmsg">Invalid approach, please use the link that has been send to your email.</div>';
}
If you visit verify.php without any strings, the follow error will be shown:
Step 7 - Login
In this final step, I will show you how to create a basic login form and check if the account is activated. First create a new file called login.php with the basic template we used before, but this time I changed the form into a login form.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>NETTUTS > Sign up</title>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<!-- start header div -->
<div id="header">
<h3>NETTUTS > Sign up</h3>
</div>
<!-- end header div -->
<!-- start wrap div -->
<div id="wrap">
<!-- start PHP code -->
<?php
mysql_connect("localhost", "tutorial", "password") or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db("registrations") or die(mysql_error()); // Select registration database.
?>
<!-- stop PHP Code -->
<!-- title and description -->
<h3>Login Form</h3>
<p>Please enter your name and password to login</p>
<?php
if(isset($msg)){ // Check if $msg is not empty
echo '<div class="statusmsg">'.$msg.'</div>'; // Display our message and add a div around it with the class statusmsg
} ?>
<!-- start sign up form -->
<form action="" method="post">
<label for="name">Name:</label>
<input type="text" name="name" value="" />
<label for="password">Password:</label>
<input type="password" name="password" value="" />
<input type="submit" class="submit_button" value="Sign up" />
</form>
<!-- end sign up form -->
</div>
<!-- end wrap div -->
</body>
</html>
The form is basic html, and almost the same as the signup form, no further explanation is needed. Now it’s time to write the code for the login script, which we will write just below the MySQL connection code. We start with something we also did in the signup form.
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['password']) && !empty($_POST['password'])){
// Both fields are being posted and there not empty
}
So we first check to see if the data is being posted, and we make sure that it’s not empty.
Next is to create some local variables for the post data:
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['password']) && !empty($_POST['password'])){
$username = mysql_escape_string($_POST['name']); // Set variable for the username
$password = mysql_escape_string(md5($_POST['password'])); // Set variable for the password and convert it to an MD5 hash.
}
We created the local variables and changed the password into a md5 hash to match it with the password hash we have stored in the database.
Now, it’s time to create the connection to our “users” table and verify if the entered data is correct.
if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['password']) && !empty($_POST['password'])){
$username = mysql_escape_string($_POST['name']);
$password = mysql_escape_string(md5($_POST['password']));
$search = mysql_query("SELECT username, password, active FROM users WHERE username='".$username."' AND password='".$password."' AND active='1'") or die(mysql_error());
$match = mysql_num_rows($search);
}
We wrote a MySQL query that will select the username, password and active information from our database, if the username and password match up.
AND active=’1′ is !IMPORTANT!, this makes sure that you can only login if your account is activated. We use the MySQL num rows again to see how many matches are found.
if($match > 0){
$msg = 'Login Complete! Thanks';
// Set cookie / Start Session / Start Download etc...
}else{
$msg = 'Login Failed! Please make sure that you enter the correct details and that you have activated your account.';
}
In the code above we check if the login was a success or not.
The End
And that’s the end of this tutorial! I hope you enjoyed it, and if you did please leave a comment below!
- Follow us on Twitter, or subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


RoyalSlider – Touch-Enable ... only $12.00 
Thanks :) , This tutorial helped me a lot !!
it help me to understand how php/mysql works *_^
Regards,
HiddeN
Excellent tutorial this not only helped the beginners but as per me the advanced segment people as well..
Well done mate
Nice Tut!
Why not consonate mt_rand four times to give a secure 16 digit key?
Занятно, хотя не мешало бы чуть поподробнее написать, а то есть немножко непонятных моментов :)
Very nice tut.
you forgot to put some ‘ ‘ to following line:
$to = ‘$comp_eu_email’;
I kep getting the error: no addresses send to header
Nice work great article , clean explanations.
thank you so much. A lot of detail in this tutorial
Nice tutorial….thx men for helping us! :)
One more thing. Really for beginers like me. Set mail server for verification.
I spend some time search how to set this.
http://www.phpeasystep.com/phptu/23.html
I hope this will help someone.
“People are always writing tut’s about membership systems etc. But never how to intergrate them into other pages.
I was thinking the other day would someone be able to write a tutorial for a member profile page.
E.g. A page that would grab the information of the selected member and display it. Maybe a bit about them selves or something…”
I too would LOVE to see a tutorial for this!!!
Thanks for this tutorial .You can find something similar here
http://youhack.me/2010/04/01/building-a-registration-system-with-email-verification-in-php/
This one also teaches you how to implement the Email Verification Feature .Happy Coding :)
your article is great. Hold on like that
thanks a lot :)
Great thanks, wouldn’t it be better to first verify the email before signing up (user, pass, etc) to stop spam more :D
i was browsing the web searching for this type of tutorial, WOW , you solved my problem mate, this is the one of the best tutorial i was able to find on the internet on the topic, thank you, keep up the good work…
Great questions! I would like to see more from where that came from.
I am a PHP/MySQL newbie. I followed this whole tutorial and all works fine for me except for one step.
I successfully get the message stating the verification link I clicked on in my email was successful and my registration is complete. I should now Login. I checked the database and see the “active” field now has “1″ in it. But I don’t have any way of getting to the login page.
Simply, how do I get from the verify.php page to the login.php page?
If your problem is being unable to see the page at all, just add a link to verify that directs you to login.php?
Awesome tutorial, exactly what I was looking for. Thank you!
highly informative and detailed.I haven’t tried it yet.Let’s see how it works……
wow. Awesome tutorial.
thank you
Interesting site, keep up the good work, my colleagues would love this. I read not a few blogs every day, and for the most part people lack substance, but not in this case. I just wanted to make a short comment to say I’m glad I found your blog, I’m gonna bookmark the net.tutsplus.com web site. Thanks
Hi Thanks for your article,anywy i has doubt on the smtp code, the verification email that we send from PHp ,actualy whe does ist generate from? it is from our code or our personal e-mail address
Awesome tutorial..!!
thanks ..!!
thanks..for this tutorial.really helpful.
YOU GUYS HELP ME ALOT. May God bless you’re
please tell me how to upload this file to cpanel and what about localhost…..
can u please write configure for cpanel phpmyadmin
This script has a bug.When I enter name and email and click sign up I get message that verification email is sent to email address.And that is OK .
But when I hit refresh on same page I enter once again same name and email into database.That is wrong,I think?
Maybe one future to put into this code.When user login would be nice to redirect to some other page different then login.php.I think that be a nice future for this login system.
This is a great tut.Nice work.
Best wishes,
Bosko
I really love this tutorial and it is about time I learn how to create this type of registration form. However, I keep getting this error “The url is either invalid or you already have activated your account.” I have a clean database and I have named all fields to match the scripts downloaded. I have tripled checked and more to see why this is doing this. It is entering it in database correctly. What should I look at here? Thanks. I really do love the tutorial though and appreciate it. Chuck
Hi,
Thanks for a nice tutorial. I came across this email component.
http://www.aspose.com/categories/.net-components/aspose.email-for-.net/default.aspx
It allowing developers to easily implement email functionality within their ASP.NET web applications, web services & Windows applications. It Supports Outlook PST, EML, MSG & MHT formats Hi there,
Great tutorial, I would just add that may be after the user is successfully it can be redirected to another page.
I guess that is just part of what we want to do with our system, although for noobies like me, it would help.
Thanks…
There’s a bit of a problem with your script. With the Login form, you’re using “name” as a column field in the database, but that was never created.
nice tutorial….
I noticed something..though, it doesn’t check if the email is already registered,
its still saves and creates duplicates..