PHP and MySQL Code

Start typing to search for PHP and MySQL Code Snippets and Articles Search

Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
Title : An email validation script that actually checks against the recipient's mail server.
Categories : Email, Complete Programs, PHP, Network, Debugging
Boaz Yahav
Date : Apr 10th 1999
Grade : 3 of 5 (graded 6 times)
Viewed : 56400
File : EmailValidation.php3
Images : No Images for this code example.
Search : More code by Boaz Yahav
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 

This script was originally written by Jon S. Stevens ([email protected]), it was
than improved by Jon S. Stevens ([email protected]).The script didn't know how
to deal with domains of the kind which have more than 2 words
after the @. I fixed that problem and also added a debugging mode which works
as a verbose mode.

By: Jon S. Stevens [email protected]
Copyright 1998 Jon S. Stevens, Clear Ink
This code has all the normal disclaimers.
It is free for any use, just keep the credits intact.

Enacements and modifications:

By: Shane Y. Gibson [email protected]
Organization: The Unix Network Archives (
Date: November 16th, 1998
Changes: Added **all** comments, as original code lacked them.
Added some return codes to include a bit more description
for useability.

By : berber
Organization :
Date : April 10th, 1999
Changes : The script now handls all kind of domains (not only @xxx.yyy) as before.
Added a debuging mode which also works as a verbose mode.


/* This function takes in an email address (say '[email protected]')
* and tests to see if it's a valid email address.
* An array with the results is passed back to the caller.
* Possible result codes for the array items are:
* Item 0: [true|false] true for valid email address
* false for NON-valid email address
* Item 1: [SMTP Code] if a valid MX mail server found, then
* fill this array in with failed SMTP
* reply codes
* Item 2: [true|false] true for valid mail server found for
* host/domain
* false if no valid mail server found
* Item 3: [MX server] if a valid MX host was found and
* connected to then fill in this item
* with the MX server hostname
* EXAMPLE code for use is at the very end of this function.

function validateEmail ( $email )
// used for SMTP HELO argument
global $SERVER_NAME;

// initialize our return array, populating with default values
$return = array ( false, "", "", "" );

// assign our user part and domain parts respectively to seperate // variables
list ( $user, $domain ) = split ( "@", $email, 2 );
if($debug_==1) {
        echo"user: $user<BR>";
        echo"domain: $domain<BR>";
// split up the domain name into sub-parts
$arr = explode ( ".", $domain );

// figure out how many parts to the host/domain name portion there are
$count = count ( $arr );

// get our Top-Level Domain portion (i.e.
$tld = $arr[$count - 2] . "." . $arr[$count - 1];

// check that an MX record exists for Top-Level Domain, and if so
// start our email address checking
if ( checkdnsrr ( $domain, "MX" ) )
        if($debug_==1) {
         echo"Check DNS RR OK<BR>";
// Okay...valid dns reverse record; test that MX record for
// host exists, and then fill the 'mxhosts' and 'weight'
// arrays with the correct information
if ( getmxrr ( $domain, $mxhosts, $weight ) )
if($debug_==1) {
                echo "MX LOOKUP RESULTS :<BR>";
                for ( $i = 0; $i < count ( $mxhosts ); $i++ ) {
                        echo "      o $mxhosts[$i]<BR>";

         // sift through the 'mxhosts' connecting to each host
for ( $i = 0; $i < count ( $mxhosts ); $i++ )
// open socket on port 25 to mxhosts, setting // returned file pointer to the
variable 'fp'
$fp = fsockopen ( $mxhosts[$i], 25 );
// if the 'fp' was set, then goto work
if ($fp)
                 if($debug_==1) {
                        echo"Socket Opened successfully<BR>";
// work variables
$s = 0;
$c = 0;
$out = "";

// set our created socket for 'fp' to
// non-blocking mode
// so our fgets() calls will return
// right away
set_socket_blocking ( $fp, false );

// as long as our 'out' variable has a
// null value ("")
// keep looping (do) until we get
// something
// output of the stream assigned
// to 'out' variable
$out = fgets ( $fp, 2500 );
                        if($debug_==1) {
                         if($out != "") echo"out: $out<BR>";
// if we get an "220" code (service ready code (i.e greeting))
// increment our work (code (c)) variable, and null
// out our output variable for a later loop test
if ( ereg ( "^220", $out ) )
                         if($debug_==1) {
                                echo"service ready on recipient machine.<BR>";
$s = 0;
$out = "";
$return[2] = true;
$return[3] = $mxhosts[$i];
// elseif c is greater than 0
// and 'out' is null (""),
// we got a code back from some
// server, and we've passed
// through this loop at least
// once
else if (($c > 0) && ($out == ""))
                         if($debug_==1) {
echo"OK so far Breaking...<BR>";
$return[2] = true;

// else increment our 's'
// counter
{ $s++; }

// and if 's' is 9999, break, to
// keep from looping
// infinetly
if ( $s == 9999 ) {
                         if($debug_==1) {
echo"Reached maximum 10000 loops, breaking.<BR>";

} while ( $out == "" );

// reset our file pointer to blocking
// mode, so we wait
// for communication to finish before
// moving on...
set_socket_blocking ( $fp, true );

// talk to the MX mail server,
// validating ourself (HELO)
fputs ( $fp, "HELO $SERVER_NAME\n" );
                 if($debug_==1) {
// get the mail servers reply, assign to
// 'output' (ignored)
$output = fgets ( $fp, 2000 );
         // give a bogus "MAIL FROM:" header to
// the server
fputs ( $fp, "MAIL FROM: <info@" . $domain . ">\n" );
                 if($debug_==1) {
echo"MAIL FROM: <info@" . $domain . "><BR>";
// get output again (ignored)
$output = fgets ( $fp, 2000 );

// give RCPT TO: header for the email
// address we are testing
fputs ( $fp, "RCPT TO: <$email>\n" );
                 if($debug_==1) {
echo"RCPT TO: <$email><BR>";
// get final output for validity testing
// (used)
$output = fgets ( $fp, 2000 );
                 if($debug_==1) {
                        echo"output : $output<BR>";
// test the reply code from the mail
// server for the 250 (okay) code
if ( ereg ( "^250", $output ) )
if($debug_==1) {
                        echo"Recipiant OK<BR>";
                        // set our true/false(ness)
// array item for testing
$return[0] = true;
// otherwise, bogus address,
// fillin the 2nd array item
// with the mail servers reply
// code for user to test if they
// want
$return[0] = false;
$return[1] = $output;
                        if($debug==1) {
                         echo"Bad Recipiant <BR>";

// tell the mail server we are done
// talking to it
fputs ( $fp, "QUIT\n" );
                 if($debug==1) {
// close the file pointer
fclose( $fp );

// if we got a good value break,
// otherwise, we'll keep
// trying MX records until we get a good
// value, or we
// exhaust our possible MX servers
if ($return[0] == true) {
                        if($debug_==1) {
                                echo"Recipiant OK... Breaking";
} else {
// No MX record appears for the specified Top-Level Domain; possibly
// an invalid host/domain name was specified.
$return[0] = false;
$return[1] = "Invalid email address (bad domain name)";
$return[2] = false;
} // end if checkdnsrr()

// return the array for the user to test against
return $return;

// Here is an example chunk of code... Normally, you'd call the
// validate email with a form or some other method to provide
// the input email address
// NOTE: You need to delete the /* and */ comment entries

// Minimal HTML code to test validateEmail() function. Save this
// to a file to test...try different email addresses in the
// 'email_address' variable field to see how it behaves.
<tilte> Validate an email address. </title>

<body bgcolor="#000000" TEXT="#FFFFCC" LINK="#33CCFF" VLINK="#9999CC" ALINK="#FFFF00">

// Assumes that you put the validateEmail() function in a file
// named "validateEmail.php3", which is in the current directory
<?php include( "validateEmail.php3" );

$email_address = "[email protected]";
$val_results = array( "", "" );

$val_results = validateEmail( $email_address );

if ( $val_results[0] == true )
$value = "<font color=\"green\">a valid</font>";
} else {
$value = "<font color=\"red\">not a valid</font>";

// print debugging info
print( "<br>Debugging Info:<br><br>" );
print( "<pre>" );
print( "(valid/not valid) <font color=\"white\">value</font> is: " . $value. "<br>");
print( "(true/false valid email) <font color=\"white\">val_results[0]</font> is: " . $val_results
[0] . "<br>");
print( "(SMTP code if false) <font color=\"white\">val_results[1]</font> is: " . $val_results
[1] . "<br>");
print( "(true/false valid MX host) <font color=\"white\">val_results[2]</font> is: " .
$val_results[2] . "<br>");
print( "(MX host that answered) <font color=\"white\">val_results[3]</font> is: " . $val_results
[3] . "<br>");
print( "</pre>" );
print( "<pre>true is represented by a 1 (one)<br>false is represented by null output</pre><br>");
// end debugging info

print( "The address <font color=\"white\"><tt>" . $email_address . "</tt></font> is " .
$value . " email address.");



Client classes for Dictionary servers UPDATED: 2000-06-06
Categories : Network, Search, Complete Programs, PHP Classes, PHP
phpDocumentor 1.1.0 - automatic documentation tool for PHP. Generates API documentation in HTML, PDF, and CHM formats with automatic linking, smart inheritance and packaging, very fast and stable. Official website
Categories : Complete Programs, Debugging, PHP, Documentation
Class for sending mail with MIME attachments in multipart format using external sendmail, mimencode and zip
Categories : Email, Network, PHP, PHP Classes
A PHP based webmail at :
Categories : Email, IMAP, PHP, Complete Programs
Categories : Complete Programs, Email, PHP
Example of function to send out email if error occurs
Categories : PHP, Email, Debugging, Errors and Logging
phpEasyMail: An easy way to send data from HTML-forms via EMail.
Categories : Email, HTML and PHP, Complete Programs, PHP
PHPRecommend v1.0 - Recommend this page to a friend script written in PHP. Easy to install
Categories : PHP, URLs, Complete Programs, Email, Site Planning
PHP port of Matt Wrights WWW form to e-mail gateway.
Categories : Email, Complete Programs, Environment Variables, PHP
PHPLinkRot v1.0 - program which allows users to report broken links on your website just by clicking a button. Works well on custom 404 pages
Categories : PHP, Complete Programs, Debugging, URLs, Site Planning
Sending email with random details
Categories : PHP, Email, Debugging
Class that allows the PHP developer to establish connections with a POP3 mail server amd be able to list, retrieve and delete mail messages from a given mail box.
Categories : Network, Email, PHP, PHP Classes
QTO File Manager
Categories : Filesystem, filePro, Complete Programs, PHP, Content Management
Clever Email Validation Function - E-Mail validation function with an eregi expression and socket connection.
Categories : Email, PHP, Regexps
PHP3: Formmail. Just a cgi formmail, but than in PHP. It is easy to use!
Categories : HTML and PHP, Email, PHP, Perl, HTML and PHP
 A. Gianotto wrote : 248
So far as I can tell, this works perfectly!  I have modified 
it a little to suit my needs, as I only needed it to return 
a message if the address was invalid.

I stuck this code in the middle of my other erro checking 

ELSEIF ( $val_results[0] == false) :  
    print "&lt;FONT FACE=\"Arial, Helvetica, Monaco, ms 
sans serif\" SIZE=\"-1\"&gt;The address " . 
$email_address . " is not a valid email address.  Please 
go back and fill in the &lt;B&gt;Email&lt;/B&gt; field with your 
correct email address";
 A. Gianotto wrote : 249
My only worry on this is what if the server is not 
reachable at that time? Also what is the timeout set 
for?  This could potentially hang the server
as dns lookups can take some time.

 Tim Smith wrote : 278
Tried it out really well except on AOL 
accounts.  Any ideas to change this?

#30 TLS
 Boaz Yahav wrote : 279
You should check the email validation class at :

 Rune Hellem wrote : 349
Worked fine for me - except on the mailserver where I 
work. My e-mail adress is [email protected], but 
if I try to send [email protected] the script 
responds with "Valid". 

The error code from the server is 551 - User unknown, 
not 550 - User unknown. Any idea how to catch this 
 DIMOS JOANNIDIS wrote : 391
Yo men what a script,
could anyone send me a html file that makes it !
i cannot understand how is this working...
i want if anyone wants to help me and gives me in my e-
mail the html and php3 file that running in my browser i 
could check the validate of an e-mail address!
Thanks,keep on ....
 Kevin Edwards wrote : 525

This would be a great script BUT seems to ignore anything before the @ ie [email protected] IS NOT a valid email address but the script say it is!

Does anyone know how to correct this?

 charles freeq wrote : 690
Another problem with this script is that it has no means of verifying email aliases.  However, I simply altered it to check the MX record to at least validate the domain.
 Sarah King wrote : 735
one of the best scripts I`ve downloaded, taken me a while to get back and say thanks but it`s been excellent at helping us tidy up (and keep tidy) our mailing lists.
 Lev Tche wrote : 843
It does not work under php/4.1.3-dev (windows bin). 

It says:
Warning: checkdnsrr() is not supported in this PHP build in c:\phpdev\www\validate\validateEmail.php on line 91

Under which versions it will work? Or I have to find some other function instead of checkdnsrr() ?
 Sean glendinning wrote : 921
I believe that this will work for windows:

function myCheckDNSRR($hostName, $recType = ``)
    if(!empty($hostName)) {
        if( $recType == `` ) $recType = "MX";
        exec("nslookup -type=$recType $hostName", $result);
        // check each line to find the one that starts with the host
        // name. If it exists then the function succeeded.
        foreach ($result as $line) {
            if(eregi("^$hostName",$line)) {
                return true;
        // otherwise there was no mail handler for the domain
        return false;
    return false;
 paul lewis wrote :1065
Some help please. I need to get the emailvalidation script working on a windows2000 server and sean suggested a function to replace the checkdnsrr() function on a windows platform. However I keep getting this error --&gt; Warning: exec() [function.exec]: Unable to fork [nslookup -type=MX] in G:........ Any help would be appreciated. Maybe there is a newer version of this script that supports windows but I have not found a link yet.