ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

How to Email Address confirmation / Verification in PHP

Updated on November 9, 2011

Introduction

In this tutorial, We will develop some php functions which are foremost tasks in email confirmation script. Email confirmation is the most easiest method,

  1. to verify person's identity,
  2. to verify whether registrant is human or machine,
  3. to just simply verify it's email for future conversations, contacts etc.

It is very easy to develop email confirmation script in php. You need not to be a professional for such task. Below are the steps that need to be followed while developing such script.

Steps TO Follow

  1. First, Generate and store activation key and activation status in database while registration,
  2. Secondly, Send an email to registrant's email ID containing activation link which will take user to activation page on our site,
  3. Activation link should contain at-least two parameters in URL, One holding registrant's 'email ID' and second one holding an 'activation key' associated with that ID. For example, "http://example.com/activation.php?email=registrant@gmail.com&key=gd7636gd7363gh8746".
  4. When, User will land on our activation page, we will fetch those parameters from the activation link and will try finding out such combination in our database,
  5. And, If such combination found, We will set activation status of associated user to active in our database.
  6. And Finally, Email has been Confirmed.

Generating Activation Key

Well, It is easy to generate any random key but we will try generating an unique key by using email address of user, See the PHP function shown below that can be used for this purpose.

PHP Function to Generate Activation KEY

function gen_activation_key($email){	
	$generatedKey = sha1(mt_rand(10000,99999).time().$email);
	return $generatedKey;
}

Sending Confirmation Email to User

Now, after generating and storing 'Activation Key' in our database, We need to send an email to registrant's Email ID containing a link pointing to our activation page. The link should contain two type of parameters,

  1. email=registrant@example.com,
  2. key=(activation key), without braces.

See the PHP function below, which would send an confirmation email to registrant (Do changes as per your requirements).

PHP Function for Sending Confirmation Email

function verificationMAIL($gKEY,$email){
	$to=$email;
	$from='do-not-reply@example.com';
	$subject='Verify your Email Address - EXAMPLE.COM';
	$headers .= 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	$mailMsg='<h2>Verify Your Email Address</h1><br />
				<a href="http://example.com/activation.php?email='.$email.'&key='.$gKEY.'">Click Here to Verify.</a>';
	mail($to,$subject,$mailMsg,$headers);
}

Confirm and Activate User

Now, When User will land on our activation page after clicking on activation link, We will fetch those email and key combination from URL and will try finding out such combination in our database. If found one, We'll set Activation status of associated user to 'Active'.

PHP Function to Confirm and Activate User

function verifyEmailAddress($email, $vkey){
		msConnect();
		$query=mysql_query("SELECT * FROM users WHERE email='$email' AND activation_key='$vkey'");
		
		$fetch=mysql_fetch_array($query);
		if($fetch['activation_status'] == 'Active'){
			$output='Your Email has already been verified.';
		}else{
			$cnt=mysql_num_rows($query);
			if($cnt=='1'){
				$updateQ=mysql_query("UPDATE users SET activation_status='Active' WHERE email='$email' AND activation_key='$vkey'");
				if($updateQ){
					$output='Email Verified';
				}else{
					$output='System Faced an error while updating your status.';
				}
			}else{
				$output='Unable to verify your email address.';
			}
		}
		mysql_close();
		return $output;
}

Important information about msConnect() function

msConnect() function above is actually a single custom build function (Doesn't exist in PHP functions Library) for connecting to and selecting a database from MySQL, You will be required to create similar one, Click here for more information.

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Max 4 years ago

      Be precise, where do we put these codes? register.php or activate.php?

    • profile image

      Florin 5 years ago

      Hi.

      Could you upload a example script that using this validation?

    • profile image

      Mr Akheel 5 years ago

      Can i use this Email service in Localhost Server...?

    • itech profile image
      Author

      Krishna 6 years ago from Dausa, India

      if(isset($_GET['key'])){

      $vkey=$_GET['key'];

      }else{

      $vkey='NotFound';

      }

      You can paste this in your script before using

      verifyEmailAddress($email, $vkey) function.

    • profile image

      David Kirui 6 years ago

      ok how do I fetch the vkey from the URL?

    • profile image

      sebastien paquet 6 years ago

      that was fast! Thank you very much.

    • itech profile image
      Author

      Krishna 6 years ago from Dausa, India

      Thanks for Commenting Sebastien...

      There is a little difference in $generatedKey and $gKEY i.e. $generatedKey (Variable) Scope is limited to function itself, therefore, it can't be accessed outside gen_activation_key() function AND $gKey is an parameter of verificationMAIL() function.

      In Short: " $gKey=gen_activation_key($email); ".

      $vKey is "Verification Key" which will fetch KEY from URL Parameter, When User will land on our webpage after clicking on verification link.

    • Sebastien Paquet profile image

      Sebastien Paquet 6 years ago

      thanks man, that's gonna be useful. I'm building a voting system. But one question I have is: You have the variable $generatedKey and $gKey, is that supposed to be the same one? and what about vKey? I'm confused.. thanks.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)