Sending E-Mail to validate User Sign-up

In one of our last tutorials we covered how to verify that a user’s email address is formatted correctly as well as verify that it goes to a valid domain name. That is great, but still not a great way to make sure a user actually owns or uses that e-mail address. This tutorial will walk you through one method of sending the user an e-mail upon signing up that gives them a link to activate their account. This will require them to click on the link in the e-mail before they can actually login to the site. Let’s get started. First, let’s create a table to hold our user information. I made a database called teamtutorials on my local server and ran this to create the table.

CREATE TABLE `users` (
  `user_id` int(7) unsigned NOT NULL auto_increment,
  `display_name` varchar(20) NOT NULL,
  `password` varchar(255) NOT NULL,
  `first_name` varchar(25) NOT NULL,
  `last_name` varchar(25) NOT NULL,
  `email_address` varchar(255) NOT NULL,
  PRIMARY KEY  (`user_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=0;

Now that the table is set up and configured the way we need it to be we can start creating the php files. We will start with the simple form file. This is adduser.php (it doesn’t have to be a php file but I do it so that If I add something later that is php it is already a php file.)

<form method="post" action="register.php" name="createuser">
	UserName:<input type="text" name="display_name" id="display_name"/><br />
	First Name:<input type="text" name="fname" id="name"/><br />
	Last Name:<input type="text" name="lname" id="surname"/><br />
	E-mail:<input type="text" name="email" id="email"/><br />
	Password:<input type="password" name="pass" id="pass"/><br />
	Confirm PW:<input type="password" name="pass2" id="pass2"/><br />
	<input type="submit" value="Sign Me Up!"/>
</form>

Next, we will need to create the register.php file that will be called when the form is submitted.

<?php
if ((!isset($_POST&#91;'display_name'&#93;))||(!isset($_POST&#91;'fname'&#93;))||(!isset($_POST&#91;'lname'&#93;))||(!isset($_POST&#91;'email'&#93;))||(!isset($_POST&#91;'pass'&#93;))){
		header('Location: http://www.teamtutorials.com');
	}
&#91;/sourcecode&#93;

First, we start the php tag and then check for the POST variables to be set. If any of them are not set it will send them back to the creation form.

&#91;sourcecode language='php'&#93;
else
	{
		$servername='localhost';
		$dbusername='dbusername';
		$dbpassword='dbpassword';
		$dbname='full db name';
		global $link;
		$link=mysql_connect ($servername,$dbuser,$dbpassword);
		if(!$link){die("Could not connect to MySQL");}
		mysql_select_db($dbname,$link) or die ("could not open db".mysql_error());
&#91;/sourcecode&#93;

If all of the POST variables are set we continue by setting the server variables and creating the database connection. Ensure that you change the variables to your server access information.

&#91;sourcecode language='php'&#93;
		$display_name = $_POST&#91;'display_name'&#93;;
		$password = $_POST&#91;'pass'&#93;;
		$first_name = $_POST&#91;'fname'&#93;;
		$last_name = $_POST&#91;'lname'&#93;;
		$email_address = $_POST&#91;'email'&#93;;
		$sha_password = sha1($password);
		$hash_string = hash('md5',$display_name);	
&#91;/sourcecode&#93;

This just stores all the values into variables that are easier to work with so we don’t have to call the POST global every time. We sha1 the password because it is not reversible so it makes it the most secure. The hash_string is a md5 hash value of the display_name so that it isn’t easily readable. We use the display name because it will be unique and specific to the user. 

&#91;sourcecode language='php'&#93;
$query = "insert into `users` values(Null,'$display_name','$sha_password','$first_name','$last_name','$email_address',0,1,CURRENT_TIMESTAMP,Null,'$company_name',8);";
		mysql_query($query) or die ("Error in query: $query " . mysql_error());
		$user_id = mysql_insert_id();
&#91;/sourcecode&#93;

Next, we insert a row into our table that we made using the variables that were passed from the form. We also get the ID of the inserted row so we know what the user id will be.

&#91;sourcecode language='php'&#93;
		$headers = "From: [email protected] \r\n";
		$validate_link = "http://teamtutorials.com/validate.php?id=$user_id&string=$hash_string";
		$email_body = "Thank-you for signing up on TeamTutorials. Click on the link below to complete your registration. If you have any issues completing the verfication please let us know. \n\n $validate_link \n\n TeamTutorials Staff";
&#91;/sourcecode&#93;

This builds all the information needed to generate an e-mail using php. The headers sets the from field so that the email will be from a user (if you don’t set this it will be nobody (the user which apache runs under in linux). The validate link is a link to the file that will validate the user when they click on it. The \n command is the php new line command.

&#91;sourcecode language='php'&#93;
		if (mail($email_address,"TeamTutorials Sign-Up",$email_body,$headers)){
			echo "Email has been sent to ".$email_address.". Please check your e-mail for steps to activate your account. Check your spam folder as sometimes these 		e-mail get marked as spam. If you still do not see your e-mail, please <a href='http://teamtutorials.com/sendemail.php?function=validation&id=$user_id'> Click Here</a> to resend.";
		}
		else
		{
			echo "There was an error sending an e-mail to your e-mail address. Please contact us to let us know of the issue.";
		}
	}
?>

Finally we attempt to send the e-mail and echo success or failure. That concludes this file. Finally we need to make the file that will validate the user when they click on the link in the e-mail that we just sent them. This file is validate.php.

<?php
if (isset($_GET&#91;'id'&#93;))&&(isset($_GET&#91;'id'&#93;)){
	$id = $_GET&#91;'id'&#93;; 
	$hashstring = $_GET&#91;'string'&#93;; 
	$storedhashvalue = "";
&#91;/sourcecode&#93;

First we make sure the values are in the url that we are expecting. At the end of the file we will re-direct them to the home page if these values aren’t set.

&#91;sourcecode language='php'&#93;
$query = "select user_id,display_name from `users` where user_id=$id;";
	$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
	$row = mysql_fetch_assoc($result);
	$storedhashvalue = hash('md5',$row&#91;'display_name'&#93;);
	mysql_free_result($result);
&#91;/sourcecode&#93;

These lines run a query against the table to get the information for the user based on the user id in the url. It then re-hashes the value so that we can compare the on in the url to match.

&#91;sourcecode language='php'&#93;
	if ($storedhashvalue == $hashstring){
		$query = "update `users` set active_flag=1 where user_id=$id;";
		$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
		echo "Your account has been activated. Please <a href='http://teamtutorials.com/login.php>Click Here To Login</a>";
	}
	else
	{
		echo "Your account could not be verified. Please verify that the link has not been modified from the e-mail. If it still does not work, please contact us.";
	}

If the values match we update the database to see the user as active and if it doesn’t work we tell them that it failed.

}
else
{
header('Location: http://www.teamtutorials.com');
}
?>

Finally we re-direct the user if the variables are not in the url. Now if you go to adduser.php and fill out the form and hit submit. It will send whatever e-mail you put in the form an e-mail with a link in it. Click on the link to activate the user. That concludes this tutorial. If you have any questions, please leave it in the comments. Thanks for viewing.

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join the TeamTutorials mailing list and get the latest tips, tricks, and special discounts for members only.

Thanks! Please click the link in the email we just sent you to confirm.

  • Excellent tip – thanks for this.

  • Thanks for this code, it will really help when looking to edit some pre-existing scripts I have.

  • Hi,it is really a nice and important article with good info related to Sending E-Mail to validate User Sign-up……..tips.

  • Thanks for this, I was looking for some information on how to do this. It can be very hard to get a validation email sent.

  • Pingback: Computers by WEB » Blog Archive » How to Parse a CSV File Using PHP()

  • This is a very nice way get this done, thanks for the tutorial.

  • Very handy and useful information to have. Thanks for including this.

  • Thank you Pamela for the information and congratulations Dr. ,

  • Is there any way to validate the form so that it dosen’t give an error message until the click “Submit”?

  • this is very helpful code thanks for sharing.

  • I am trying to learn the basis of email validation. Great tutorial Mike, hope to see more in the future.

  • mehmet

    when person sing up site from form.for example thingthey have another table for example message box table how can u copy same id for message box too

  • Chander Kamal

    Marvelous, im in search of it from last 1 month

  • Hi Thankx that a Goooood turotial please can any body send em complete code file
    i mtrying to note this step by step but facing some problem
    coz i m beginner in php
    plz can any body help me
    waiting for

  • Ben

    This will come in handy for a web server I plan on making. Thanks for this tips.

  • Dear All Programmer

    Please give me php coding for search SQL table from all data print/show

    with Thanks
    Nurmohammad

  • Pradeep_ujjapla

    Dear programmer.

    i need uploading files and storing in to the database in this form only, what is the code for this, please suggest me.