Mindphp.com เว็บ สอนสร้างเว็บไซต์ ฐานข้อมูล php Javascript Ajax Jquery Html CSS CMS CRM และ เว็บเซอเวอร์ Hosting Web Server สอน Joomla phpbb JpGraph

E-mail validation with PHP 4

เทคนิค การเขียน PHP

E-mail validation with PHP 4

By John Coggeshall
April 17, 2001
Prev Next


Introduction
The problem with e-mail addresses
E-mail format matching with regular expressions
What is a regular expression?
Practical regular expressions
The regular expression e-mail pattern
Using the e-mail server
Finding the e-mail server
Connecting to the e-mail server
Communicating with the mail server
The script
Step 1 -- Initialize the script
Step 2 -- Check the e-mail address format
Step 3 -- Find the address of the mail server
Step 4 -- Connect to mail server and check e-mail address (OPTIONAL)
Step 5 -- Return the results

Introduction

This week, you'll learn how to validate an e-mail address in PHP 4. You can do this by its format, as well as by actually contacting the appropriate mail server and optionally checking to see if the e-mail address submitted actually exists. You'll accomplish this through topics I covered in a previous article, Connecting to Internet Services, and "ifsnow2" with their contribution, Clever E-mail Validation Function.

Validating an e-mail address can be a tricky process. If you look in our own Code Gallery, you'll find numerous methods ranging in complexity. They're all trying to determine, one way or another, if the e-mail address supplied actually exists.

This week, I've gone through most of these validation functions and have brought you the one that I feel not only has the most educational value, but also does the best job accomplishing the goal. You'll also learn about our Code Gallery Spotlight contribution, and the four steps (plus an additional optional step) to help ensure that the e-mail address it was given was indeed valid.

The problem with e-mail addresses

Validating e-mail address seems like a fairly simple task. At first glance, it looks as if you just need to ensure that the e-mail address follows this format:

@.

However, it's not that simple. The username, domain, and suffix aren't just any string -- they all have requirements, such as spaces are not allowed. Also, the domain itself isn't always a single string, but could resemble this:

@..

Then of course, the suffix has specific requirements (i.e., has to be a .com, .net, etc.).

Realistically, it would be impossible for me to cover all of the format requirements of an e-mail address in depth in a single article. However, for our purposes, we have covered all of the major requirements. In addition, there is no guarantee that just because a given string resembles an e-mail address that it actually is a valid e-mail address.

So how do you deal with so many requirements? I'll show you how you can use PHP regular expressions and connectivity functions to do a reasonable job.

E-mail format matching with regular expressions

What is a regular expression?

A regular expression is a method for matching complex string patterns (such as an e-mail address) through the use of other specially constructed strings called regular expressions. There are numerous methods in PHP to take advantage of regular expressions, but in this column I'll introduce ereg() and eregi().

These two functions are nearly identical in function, with slight, yet important differences (eregi() is case insensitive). The syntax for these two functions is also identical:

int ereg(, , )

Note: the syntax for eregi is identical; simply replace ereg with eregi

Needle is our regular expression; haystack represents the string that the search is to be performed on. Finally, array will be the variable to store an array of return results (consisting of the different "segments" of the match that are denoted by parentheses in the regular expression pattern).

Practical regular expressions

The first step when validating an e-mail address is to check its format. Of course, this will be done through the use of regular expressions. If you are familiar with regular expressions, you should have little trouble understanding the pattern matching string below.

Unfortunately, if you are unfamiliar with regular expressions, (or were just introduced them above) there is no choice to accept the expression below at face value. Regular expressions and their use is the topic of entire books, and cannot be covered in a meaningful way within the confines of this article.

If you're interested in learning about regular expressions, there are numerous online tutorials online, which can be found on most PHP or Perl resource sites. If you're interested in published materials on regular expressions, read O'Reilly's "Mastering Regular Expressions".

The regular expression e-mail pattern

The expression below represents the regular expression to match the format of an e-mail address:

^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$

Although complex and cryptic, if you have minimal experience with regular expressions, you should make the above regular expression at least understandable -- even if you couldn't write it yourself. In actual PHP code, the above regular expression could be used in the following manner to check the validity of an e-mail address:

$email=" อีเมลนี้จะถูกป้องกันจากสแปมบอท แต่คุณต้องเปิดการใช้งานจาวาสคริปก่อน ";

if(!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-
]+)*(.[a-z]{2,3})$", $email) {

echo "The e-mail was not valid";

} else {

echo "The e-mail was valid";

}

?>

Using the e-mail server

Once you have validated the format of an e-mail address, you can take the script a step further and do a little on-the-fly confirmation of the existence of at least an e-mail server associated with a given e-mail address. Once the server is found, optionally you can attempt to further confirm the existence of the address by contacting the server directly.

The first step would be to try to locate the appropriate mail server, and that's where I'll start.

Finding the e-mail server

In order to confirm the existence of the specified e-mail address, you need to get in touch with the mail server that maintains that e-mail address directly. But in order to contact that e-mail server, you'll need to know its address. With only the e-mail address itself, you'll need to do a little homework.

The first step is to determine the domain from which the e-mail supposedly originated. You can do this by splitting apart the e-mail address using the split() function.

list($username, $domain) = split('@', $email);
?>

Note the use of the list() function to directly assign the values returned by the split() variable. This saves us the extra step of assigning the variables directly and makes the code a bit cleaner.

The next step is to take the domain name you retrieved, and see if a mail server has been registered for the domain name. You can do this with the getmxrr() function. If there is a mail server registered for the domain, save it, should you want to contact it later. If this is the case and no mail server is registered, assume that the domain name provided is also the address for the mail server, and you should save that.

With our best choice for the mail server in hand, our next step is to actually connect to the server.

Connecting to the e-mail server

Important Note: The following is an optional step to provide a secondary means of validating our e-mail address. Because of the configuration of some mail servers, the additional validation check below is unreliable and sometimes will incorrectly confirm the existence of e-mail addresses when the server is set to route all mail to unknown persons to a valid predetermined account. It is included simply to explain the code as it was presented in the gallery, and hopefully to further educate you in PHP/server interactions. For the purposes of this section, assume that the server will respond as we would hope, and inform us if the specific e-mail address in question exists.

In order to connect to the mail server, you'll use basically the same methods I used in my Connecting to Internet Services article. It simply involves using the fsockopen() to open a connection to the mail server (port 25) and using the standard fputs() and fgets() to communicate. What to communicate is another matter entirely.

Communicating with the mail server

Once a connection has been made to the mail server, you need to use the SMTP (Simple mail transfer protocol) to communicate with the mail server. The goal here is not to actually send an e-mail, but rather to look like you are sending an e-mail. When a mail server receives a request to send an e-mail within its domain, it confirms that the account the e-mail is addressed to exists. Therefore, if we attempt to send an e-mail and the e-mail is rejected by the server, we can confidently say that e-mail address is a fraud.

Unfortunately, the converse is not as helpful. If our attempt to send an e-mail to the address we would like to check succeeds, we do not have the same level of confidence that the e-mail address exists as we did when the check failed. This is because mail servers, depending on their administrator's wishes, can be configured to accept all e-mail to its domain, regardless of whether the account actually exists.

However, before you can communicate with the server, you need to know the proper protocol. For the purposes of this article, I'll just give you a rundown of the "conversation" between client and sever:

220 X1 Welcome to zend.com's SMTP Service!

HELO localhost

250 hello

MAIL FROM:

250 ok

RCPT TO:

550 unknown user

QUIT

221 Goodbye

In this instance, you can see that the user อีเมลนี้จะถูกป้องกันจากสแปมบอท แต่คุณต้องเปิดการใช้งานจาวาสคริปก่อน didn't exist. However, if the e-mail address you addressed our e-mail to had existed, the result would have been something like...

250 ok its for

...instead of the 550 error code you did receive.

Note: Server messages can, and often do, change from server to server. So when you check the results from a mail server command, search for the result code (the three-digit number at the beginning of every response), rather than a specific message.

Now that you know how to:

  • check the format of an e-mail address
  • hunt down the appropriate mail server
  • check with the server to ensure the address exists

... it's time to look at the script!

The script

The entire script is encapsulated within a single function ValidateMail() that will return an array telling you whether the e-mail address was valid. If it wasn't, you'll get an error message telling you where the process failed.

Step 1 -- Initialize the script

The first step in any script, of course, is to initialize any variables you'll be using. In this case, declare any global variables you'll be using:

function ValidateMail($Email) {
global $HTTP_HOST;
$result = array();

Step 2 -- Check the e-mail address format

Next, you'll use our regular expression to determine if the e-mail address is properly formatted. If the e-mail address is not valid, return in error:

if (!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $Email)) {

$result[0]=false;
$result[1]="$Email is not properly formatted";
return $result;
}

Step 3 -- Find the address of the mail server

Now, split apart the e-mail address and use the domain name to search for a mail server you can use to further check the e-mail address. If no mail server is found, you'll just use the domain address as a mail server address:

Note: In the event that the optional step 4 is not followed, the else portion of this step must return in error in order for the script to function properly.


list ( $Username, $Domain ) = split ("@",$Email);

if (getmxrr($Domain, $MXHost)) {

$ConnectAddress = $MXHost[0];
} else {

$ConnectAddress = $Domain;

}

Step 4 -- Connect to mail server and check e-mail address (OPTIONAL)

Finally, once you have the best guess at a mail server, it's time to open a connection and talk to the server. As I stated earlier, this step is optional. After every command you send, you'll need to read a kilobyte (1024 bytes) of data from the server. It should be more than enough to receive the complete response from the server for that command.

Note that you'll store the output from the server in three separate variables: $To, $From and $Out. This is done so you can check the responses after you close the connection, to see if you actually have a real e-mail address or not.

If the script cannot connect at all, or the e-mail address wasn't valid, set the $result array to the proper values:


$Connect = fsockopen ( $ConnectAddress, 25 );

if ($Connect) {

if (ereg("^220", $Out = fgets($Connect, 1024))) {

fputs ($Connect, "HELO $HTTP_HOST ");
$Out = fgets ( $Connect, 1024 );
fputs ($Connect, "MAIL FROM: <{$Email}> ");
$From = fgets ( $Connect, 1024 );
fputs ($Connect, "RCPT TO: <{$Email}> ");
$To = fgets ($Connect, 1024);
fputs ($Connect, "QUIT ");
fclose($Connect);
if (!ereg ("^250", $From) ||
!ereg ( "^250", $To )) {
$result[0]=false;
$result[1]="Server rejected address";
return $result;

}
} else {

$result[0] = false;
$result[1] = "No response from server";
return $result;
}

} else {

$result[0]=false;
$result[1]="Can not connect E-Mail server.";
return $result;
}

Step 5 -- Return the results

Finally, our last and easiest step is to return the results and finish:

$result[0]=true;
$result[1]="$Email appears to be valid.";
return $result;
} // end of function
?>

About John Coggeshall

John Coggeshall is a PHP consultant and author who started losing sleep over PHP around five years ago. Lately you'll find him losing sleep meeting deadlines for books or online columns on a wide range of PHP topics. You can find his work online at O'Reilly Networks onlamp.com and Zend Technologies, or at his website http://www.coggeshall.org/.

John has also contributed to WROX Press' Professional PHP4 Programming and is currently in the progress of writing the PHP Developer's Handbook published by Sams Publishing.




User Rating: / 0
แย่ดีที่สุด 

หน้าเว็บบอร์ด Programming - PHP ตั้งกระทู้ใหม่ ใน Programming - PHP, phpBB3, SMF, Joomla, Wordpress, CMS CRM ตั้งกระทู้ใหม่ ใน phpBB3, SMF, Joomla, Wordpress, CMS CRM, JavaScript & Jquery Ajax ตั้งกระทู้ใหม่ ใน JavaScript & Jquery Ajax, SQL - Database ตั้งกระทู้ใหม่ ใน SQL - Database, ถาม - ตอบ คอมพิวเตอร์ ตั้งกระทู้ใหม่ ใน ถาม - ตอบ คอมพิวเตอร์, PHP Knowledge ตั้งกระทู้ใหม่ ใน PHP Knowledge, PHP News ตั้งกระทู้ใหม่ ใน PHP News, HTML CSS ตั้งกระทู้ใหม่ ใน HTML CSS, Free PHP Code Download script ตั้งกระทู้ใหม่ ใน Free PHP Code Download script, Web Hosting Review - Free Host Share Host VPS ตั้งกระทู้ใหม่ ใน Web Hosting Review - Free Host Share Host VPS
หัวข้อกระทู้ ตอบ เปิดดู โดย
รบกวนสอบถามการรับค่าจาก textfile
โดย butterney 2012/05/15 19:16 บอร์ด Programming - PHP
6 120 2012/05/16 20:41
โดย butterney
มีปัญหาอ้ะครับ มาช่วยหน่อยนะครับ
โดย namkabz 2012/05/17 01:19 บอร์ด Programming - PHP
0 34 2012/05/16 18:19
โดย namkabz
สอบถาม เรื่อง "การสร้างดาต้าเบสสำหรับ Backup ครับ"
โดย Chayyim 2012/05/16 23:05 บอร์ด SQL - Database
0 41 2012/05/16 16:05
โดย Chayyim
ช่วยหน่อยคัฟ ไม่เก่ง PHP แต่พึ่งเริ่มทำงาน ติดปัญหาซะแร้ววว
โดย M&N 2012/05/04 16:03 บอร์ด Programming - PHP
3 431 2012/05/16 15:54
โดย tohkai_php
HTML5 สำหรับ Yii Framework
โดย mindphp 2012/04/17 09:32 บอร์ด PHP Knowledge
1 296 2012/05/16 15:50
โดย tohkai_php
รับสมัครพนังงานต่ำแหน่ง it support ครับ
โดย tohkai_php 2012/05/16 22:44 บอร์ด PHP News
0 46 2012/05/16 15:44
โดย tohkai_php
html5 + javascript เสมือน apps mobile เนียนมากๆครับ
โดย tohkai_php 2012/05/16 22:43 บอร์ด Free PHP Code Download script
0 45 2012/05/16 15:43
โดย tohkai_php
รบกวนขอความรู้ครับ
โดย Sum76 2009/02/06 20:13 บอร์ด Programming - PHP
3 398 2012/05/16 10:50
โดย malangtub
ขั้นตอนการทำงาน ระหว่าง Client - เว็บไซต์เรา และ facebook
โดย mindphp 2011/12/13 08:08 บอร์ด Programming - PHP
1 582 2012/05/16 10:45
โดย malangtub
ใช้ php สร้าง WebServices ด้วย PHPSoap
โดย batman1292 2012/05/08 03:02 บอร์ด PHP Knowledge
5 666 2012/05/16 10:35
โดย malangtub
ถามเกี่ยวกับสคริป php หน่อยคับ โทษทีถ้าถามผิดห้อง
โดย youscoms 2012/04/24 01:49 บอร์ด Programming - PHP
4 623 2012/05/16 10:24
โดย บุคคลทั่วไป
ปัญหาการติดตั้ง magento Database connection error.
โดย docman 2012/04/24 21:13 บอร์ด Programming - PHP
2 336 2012/05/16 10:22
โดย malangtub
php มีคำสั่ง block แถบเมนูไหมค่ะ
โดย NatoOne 2012/04/21 23:01 บอร์ด Programming - PHP
6 590 2012/05/16 10:21
โดย malangtub
Count down Javascript โปรเจ็คเกี่ยวกับการทำข้อสอบ
โดย ultraman_neww 2012/05/06 02:50 บอร์ด Programming - PHP
4 453 2012/05/16 10:16
โดย malangtub
ถามเกี่ยวกับหน้า login และ timestamp หน่อยครับ
โดย OneLifeBegin 2012/04/24 18:25 บอร์ด Programming - PHP
13 1611 2012/05/16 08:41
โดย ekaja
ที่ตั้งการ upload
โดย Pleumiie 2012/04/24 23:08 บอร์ด Programming - PHP
6 391 2012/05/16 08:30
โดย ekaja
เพิ่มพลังในการทำงานด้วยสิ่งนี้ดีกว่า อิอิ
โดย oliveen 2012/05/15 23:24 บอร์ด โหลดโปรแกรม พูดคุยเรื่องทั่วไป จับฉ่าย
1 242 2012/05/15 16:24
โดย starseed
มีปัญหาตารางของฐานข้อมูลมันแสดงขึ้นมาว่า "in use" ครับ
โดย Nakorn1911 2012/05/15 01:53 บอร์ด SQL - Database
3 154 2012/05/15 13:33
โดย Nakorn1911

New Members

sirintra : 16/05/2012 ปาริชาติ รัชฎาศรี : 16/05/2012 margarin : 16/05/2012 Chayyim : 16/05/2012 masteriii : 16/05/2012 ekaja : 16/05/2012 starseed : 15/05/2012 chanthasone : 15/05/2012 butterney : 15/05/2012 True_net : 15/05/2012 bethezank : 15/05/2012 potae2424 : 15/05/2012 theoldza123 : 14/05/2012 nano  kigk : 14/05/2012 numtip : 14/05/2012 bonus82 : 13/05/2012 momay : 13/05/2012 ploy171499 : 13/05/2012 kai2104 : 12/05/2012 ouizzzz : 11/05/2012