Webmaster Forum

Go Back   Webmaster Forum > Webmaster Discussion Forums > Web Design and Graphics

Notices

Reply
 
LinkBack Thread Tools Display Modes
Old 05-17-2008, 03:48 PM   #1
New Member
 
Join Date: May 2008
Posts: 14
Credits: 1
Sarunas is on a distinguished road
Default [PHP] Email Validation

Email Validation is a common thing that is done on all/most signup pages, doesn't matter which website it may be.
These types of scripts are not that hard to create, but most struggle to make it.

Another thing with most email validation scripts is that it is inaccurate, you can enter something like blah@thisdomaindoesnotexist.gah and it will return as a valid email address, here is a script just as that, feel free to check my theory(this is the fourth result from googling "Email validation PHP").

This is because of poor validation, normally something like the following is used in most validation scripts:
Code:
ereg("^[a-zA-Z0-9_]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$]", $email)
It is not only done in PHP, but also in Javascript, most people think that form validation with javascript is good, but they are just so wrong.

In this post, I will be giving examples of a few types of email validation script that can be used in PHP.


Example 1
This will look at the email address, split it up into a username, domain name and a suffix.
Code:
<?php
function validate_mail($address) {
	if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $address)) return false;
	else {
		$email_parts = explode('@', $address, 2);
		$domain_parts = explode('.', $email_parts[1]);
		for ($i = 0; $i < count($local_array); $i++) {
			if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~.-]{0,63})|("[^(\|")]{0,62}"))$",
			$local_array[$i])) {
				$returned = true;
				return false;
			} 
		}
		if (empty($returned) && (ereg("^[?[0-9.]+]?$", $email_parts[1]) || count($x = explode('.', $email_parts[1])) < 2)) {
			return false;
		}
		else {
			for ($i = 0; $i < count($domain_array); $i++) {
				if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_parts[$i])) {
					$returned = true;
					return false;
				}
			}
		}
		if (empty($returned)) return true;
	}
}
?>
Example 2
Doing a basic check if the email is valid, and then sending a email to the user, where they will find a link to activate their account.
This is the long way around, and requires much more things to be done, like making an extra row in the user table(I'm going to skip the mysql parts).

Code:
<?php
function valemail($address, $username, $password, $dir='validations') {
	if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $address)) return false;
	else {
		if (empty($username) || empty($password)) return false;
		else {
			$filename = $username . md5($address);
			$key = sha1($filename);
			$fp = fopen($dir . '/' . $key, 'w');
			fputs($fp, base64_encode("INSERT INTO `users` (`id`, `name`, `email`, `password`) VALUES (NULL, '" . 
			$username . "', '" . $address . "', '" . $password . "')"));
			fclose($fp);
			$headers = "From: you@domain.suffix <group youdomain>rn" .
				   	   "Reply-to: reply@domain.suffixrn";
			$content = "Thank you for signing up at our website.rn" . 
				   	   "In order for you to login to your account, you will first need to activate your account.rnrn" .
				   	   "Please verify that the following information is correct before you continue:rn" . 
				   	   "Account: " . $username . "rn" .
				   	   "Password: " . $password . "rn" . 
				   	   "rnIf all of the above information is correct, please continue by following the link below.rn" . 
				   	   $validate_link . "(<a href="" . $validate_link . "">AOL</a>)rnrn" . 
				   	   "If you did not create this account, please follow the link below.rn" . 
				   	   $suspend_link . "(<a href="" . $suspend_link . "">AOL</a>)rnrnrn" . 
				   	   "Regards,rn" . 
				   	   "YourDomain";
			$mail = mail($address, 'Account Signup: ' . $username, $content, $headers);
			if (!empty($mail)) return false;
			else return true;
		}
	}
}
?>
Code:
<?php
function valaccount($key, $dir='validations', $suspend=false) {
	if (strlen($key) != 32 || empty(file_exists($dir . '/' . $key))) return false;
	else if (!empty($suspend)) {
		unlink($dir . '/' . $key);
		return true;
	}
	else {
		$fp = fopen($dir . '/' . $key, 'r');
		$contents = '';
		while(!feof($fp)) $contents .= fgets($fp, 1024);
		fclose($fp);
		unlink($dir . '/' . $key);
		$contents = base64_decode($contents);
		$split = explode('_.', $contents);
		if ($split[0] <= (time()-1800)) return false;
		else {
			$query = mysql_query($split[1]);
			if (!empty($query)) return true;
			else return false; 
		}
	}
}
?>
Both functions is needed, using them is very simple.
You can use both of the examples together, to make an even more accurate validation, but it is optional.

Here is a example for each of the two examples:
Example 1
Code:
<?php
if (!empty($_POST['address'])) {
	exit('<p>The following email address is <b>' . 
	     ((!valmail($_POST['address'])) ? 'Invalid' : 'Valid') . 
	     '</b>!<br>' . 
		 $_POST['address'] . '</p>');
}

echo '<p><form method="post">
	  Email: <input name="address"><br>
	  <input type="submit" value="validate">
	  </form></p>';
?>
Example 2
This will use both examples to make a very accurate validation.
Code:
<?php
if (!empty($_POST['address'])) {
	$result = valemail($_POST['address'], htmlspecialchars($_POST['name']), $_POST['password']);
	if (empty($result)) echo 'We were unable to verify your email address.';
	else echo 'We have sent an email to the address you specified, please review the message and follow the instructions.';
}
else if (count($url = explode(':', $_SERVER['QUERY_STRING'])) == 2) {
	switch ($url[0]) {
		case 'act' : 
				$result = valaccount($url[1]);
				if (empty($result)) {
					echo 'You have supplied an invalid activation key, ' . 
					'or you activation has expired.';
				}
				else {
					echo 'Your account has been activated!<br>You may no' . 
					'w proceed to the login page.';
				}
				break;
		case 'spd' : 
				$result = valaccount($url[1], 'validations', true);
				if (empty($result)) {
					echo 'You have supplied an invalid activation key, ' . 
					'or you activation has expired.';
				}
				else echo 'Your account has been deleted.';
				break;
		default : echo 'Invalid request.'; break;
	}							 
}
else {
	echo '<p><form method="post">
	 	 Name: <input name="name"><br>
	 	 Password: <input name="password"><br>
	 	 Email: <input name="address"><br>
	 	 <input type="submit" value="validate">
	 	 </form></p>';
}
?>
If you have any questions, please reply to this thread.

*NOTE* PHP Experience required to understand a few commands in the instructions...

?Sarunas
Sarunas is offline   Reply With Quote
Old 05-21-2008, 01:22 PM   #2
Counting 10,000 :D
 
Swastik's Avatar
 
Join Date: Mar 2008
Location: India
Posts: 494
Credits: 0
Swastik has a spectacular aura aboutSwastik has a spectacular aura about
Send a message via MSN to Swastik Send a message via Yahoo to Swastik
Default

Wow! Quite insightful .
Swastik is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
Email mailing script? Versace Web Design and Graphics 3 Today 07:31 AM
[PHP] Wordpress coding, got any tips? Ikki Web Design and Graphics 3 06-17-2008 08:04 PM
How to Email Post for Wordperss Jacki Blogging Discussion 0 05-17-2008 01:11 AM



vBCredits v1.4 Copyright ©2007 - 2008, PixelFX Studios