ให้เรตสมาชิก: 1 / 5

ดาวใช้งานดาวไม่ได้ใช้งานดาวไม่ได้ใช้งานดาวไม่ได้ใช้งานดาวไม่ได้ใช้งาน
 
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="john@zend.com";

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 mystery@zend.com 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.




กระทู้ล่าสุดจากเว็บบอร์ด
หัวข้อกระทู้
ตอบ
เปิดดู
ล่าสุด
งานประจำวันที่ 2 มิถุนายน 2563
โดย natthanit.r2538 อ 02 มิ.ย. 2020 10:11 am บอร์ด M103 - ณัฐนิตย์ ร่มบ้านโหล๊ะ
4
31
อ 02 มิ.ย. 2020 7:42 pm โดย natthanit.r2538
มารู้จักจังหวัดสงขลา เมืองสองทะเลกันค่ะ
โดย natthanit.r2538 อ 02 มิ.ย. 2020 4:27 pm บอร์ด M103 - ณัฐนิตย์ ร่มบ้านโหล๊ะ
0
7
อ 02 มิ.ย. 2020 4:27 pm โดย natthanit.r2538
ระบบบัญชีคืออะไร มีความสำคัญอย่างไร และจะทำอย่างไรหากต้องการวางระบบบัญชี
โดย natthanit.r2538 อ 02 มิ.ย. 2020 2:13 pm บอร์ด M103 - ณัฐนิตย์ ร่มบ้านโหล๊ะ
0
4
อ 02 มิ.ย. 2020 2:13 pm โดย natthanit.r2538
เปิดบริษัทต้องจดทะเบียนภาษีมูลค่าเพิ่มหรือไม่ ภาษีมูลค่าเพิ่มคืออะไร ??
โดย natthanit.r2538 อ 02 มิ.ย. 2020 12:16 pm บอร์ด M103 - ณัฐนิตย์ ร่มบ้านโหล๊ะ
0
7
อ 02 มิ.ย. 2020 12:16 pm โดย natthanit.r2538
ภ.ง.ด. 1,3,53 คืออะไร
โดย natthanit.r2538 อ 02 มิ.ย. 2020 11:08 am บอร์ด M103 - ณัฐนิตย์ ร่มบ้านโหล๊ะ
0
7
อ 02 มิ.ย. 2020 11:08 am โดย natthanit.r2538
สรุปการประชุมลูกค้าครั้งแรก
โดย natthanit.r2538 จ 01 มิ.ย. 2020 6:46 pm บอร์ด M103 - ณัฐนิตย์ ร่มบ้านโหล๊ะ
0
2
จ 01 มิ.ย. 2020 6:46 pm โดย natthanit.r2538
สวนครัวริมระเบียง
โดย natthanit.r2538 จ 01 มิ.ย. 2020 4:42 pm บอร์ด M103 - ณัฐนิตย์ ร่มบ้านโหล๊ะ
0
10
จ 01 มิ.ย. 2020 4:42 pm โดย natthanit.r2538
วิธีการเดินทางจาก สงขลา มา กรุงเทพฯ
โดย natthanit.r2538 จ 01 มิ.ย. 2020 1:47 pm บอร์ด M103 - ณัฐนิตย์ ร่มบ้านโหล๊ะ
0
17
จ 01 มิ.ย. 2020 1:47 pm โดย natthanit.r2538
งานประจำวันที่ 1 มิถุนายน 2563
โดย natthanit.r2538 จ 01 มิ.ย. 2020 10:53 am บอร์ด M103 - ณัฐนิตย์ ร่มบ้านโหล๊ะ
2
32
อ 02 มิ.ย. 2020 10:00 am โดย natthanit.r2538
note
โดย natthanit.r2538 จ 01 มิ.ย. 2020 10:52 am บอร์ด M103 - ณัฐนิตย์ ร่มบ้านโหล๊ะ
0
6
จ 01 มิ.ย. 2020 10:52 am โดย natthanit.r2538
Work's on Hand ณัฐนิตย์ ร่มบ้านโหล๊ะ M103
โดย natthanit.r2538 จ 01 มิ.ย. 2020 10:49 am บอร์ด M103 - ณัฐนิตย์ ร่มบ้านโหล๊ะ
0
4
จ 01 มิ.ย. 2020 10:49 am โดย natthanit.r2538
list ความรู้ที่มี ว่าเคยเรียน หรือ เคยทำอะไรมาบ้าง
โดย natthanit.r2538 จ 01 มิ.ย. 2020 10:48 am บอร์ด M103 - ณัฐนิตย์ ร่มบ้านโหล๊ะ
2
23
จ 01 มิ.ย. 2020 11:08 am โดย natthanit.r2538
B - เข้าเมนูหน้ารวมรายการใน admin ไม่ได้
โดย thatsawan ศ 29 พฤษภาคม 2020 5:58 pm บอร์ด Odoojob.com - Tester
0
1
ศ 29 พฤษภาคม 2020 5:58 pm โดย thatsawan
B - ยังขาดหน้าผลการค้นหา จาก search.php
โดย mindphp ศ 29 พฤษภาคม 2020 6:11 am บอร์ด FDD (Main)
0
1
ศ 29 พฤษภาคม 2020 6:11 am โดย mindphp
B - กล่องค้นหาจากหน้า index ใช้งานไม่ได้ กดแล้วไม่ไปหน้าค้นหา
โดย mindphp ศ 29 พฤษภาคม 2020 5:39 am บอร์ด FDD (Main)
1
1
ศ 29 พฤษภาคม 2020 5:53 am โดย mindphp
B - ไม่ใช่แค่โชว์ icon facebook มันต้องทำลิงค์เพื่อให้คลิกไป
โดย mindphp ศ 29 พฤษภาคม 2020 4:39 am บอร์ด FDD (Main)
1
2
ศ 29 พฤษภาคม 2020 4:51 am โดย mindphp
อัพเดท phpbb 3.3 เเล้ว extenstion ใช้งานไม่ได้
โดย thatsawan พฤ 28 พฤษภาคม 2020 10:08 pm บอร์ด ปัญหาการใช้ phpBB3, SMF, Joomla, Wordpress, CMS, CRM
1
125
พฤ 28 พฤษภาคม 2020 10:10 pm โดย thatsawan
วิธีการสร้าง css ที่ใช้งานเฉพาะในบราวเซอร์ safari เท่านั้น
โดย Ittichai_chupol พฤ 28 พฤษภาคม 2020 6:06 pm บอร์ด CSS Knowledge
0
121
พฤ 28 พฤษภาคม 2020 6:06 pm โดย Ittichai_chupol
R - Set Demo เป็น subdomain ของ ตัวนี้
โดย mindphp พฤ 28 พฤษภาคม 2020 6:17 am บอร์ด มารียา ซีฟู้ดส์ - Developer
0
9
พฤ 28 พฤษภาคม 2020 6:17 am โดย mindphp
อยากทราบวิธีการกำหนด ค่า css ให้กับ button โดยกำหนดเฉพาะแต่ละบราวเซอร์
โดย Ittichai_chupol พ 27 พฤษภาคม 2020 8:39 pm บอร์ด HTML CSS
1
52
พ 27 พฤษภาคม 2020 9:15 pm โดย mindphp