/    Sign up×
Community /Pin to ProfileBookmark

E-mail validator query ….

I have got the following code written for validating an email address. The function StrChkInv($em) is incomplete it will check for invalid characters and return true if not found or false if found.

[code=php]<?PHP

function StrChkInv($em)
{}

function ChkEm($em)
{
if(strpbrk($em, ‘@’))
{
return true;

}
}

/*Checks for validity of domain name*/
function ChkDom($em)
{
/* Three character domain names */
$dm1 = array(
‘.ac’, ‘.ad’, ‘.ae’, ‘.af’, ‘.ag’, ‘.ai’, ‘.al’, ‘.am’,
‘.an’, ‘.ao’, ‘.aq’, ‘.ar’, ‘.as’, ‘.at’, ‘.au’, ‘.aw’,
‘.az’, ‘.ba’, ‘.bb’, ‘.bd’, ‘.be’, ‘.bf’, ‘.bg’, ‘.bh’,
‘.bi’, ‘.bj’, ‘.bm’, ‘.bn’, ‘.bo’, ‘.br’, ‘.bs’, ‘.bt’,
‘.bv’, ‘.bw’, ‘.by’, ‘.bz’, ‘.ca’, ‘.cc’, ‘.cd’, ‘.cf’,
‘.cg’, ‘.ch’, ‘.ci’, ‘.ck’, ‘.cl’, ‘.cm’, ‘.cn’, ‘.co’,
‘.cr’, ‘.cu’, ‘.cv’, ‘.cx’, ‘.cy’, ‘.cz’, ‘.de’, ‘.dj’,
‘.dk’, ‘.dm’, ‘.do’, ‘.dz’, ‘.ec’, ‘.ee’, ‘.eg’, ‘.eh’,
‘.er’, ‘.es’, ‘.et’, ‘.fi’, ‘.fj’, ‘.fk’, ‘.fm’, ‘.fo’,
‘.fr’, ‘.ga’, ‘.gd’, ‘.ge’, ‘.gf’, ‘.gg’, ‘.gh’, ‘.gi’,
‘.gl’, ‘.gm’, ‘.gn’, ‘.gp’, ‘.gq’, ‘.gr’, ‘.gs’, ‘.gt’,
‘.gu’, ‘.gw’, ‘.gy’, ‘.hk’, ‘.hm’, ‘.hn’, ‘.hr’, ‘.ht’,
‘.hu’, ‘.id’, ‘.ie’, ‘.il’, ‘.im’, ‘.in’, ‘.io’, ‘.iq’,
‘.ir’, ‘.is’, ‘.it’, ‘.je’, ‘.jm’, ‘.jo’, ‘.jp’, ‘.ke’,
‘.kg’, ‘.kh’, ‘.ki’, ‘.km’, ‘.kn’, ‘.kp’, ‘.kr’, ‘.kw’,
‘.ky’, ‘.kz’, ‘.la’, ‘.lb’, ‘.lc’, ‘.li’, ‘.lk’, ‘.lr’,
‘.ls’, ‘.lt’, ‘.lu’, ‘.lv’, ‘.ly’, ‘.ma’, ‘.mc’, ‘.md’,
‘.mg’, ‘.mh’, ‘.mk’, ‘.ml’, ‘.mm’, ‘.mn’, ‘.mo’, ‘.mp’,
‘.mq’, ‘.mr’, ‘.ms’, ‘.mt’, ‘.mu’, ‘.mv’, ‘.mw’, ‘.mx’,
‘.my’, ‘.mz’, ‘.na’, ‘.nc’, ‘.ne’, ‘.nf’, ‘.ng’, ‘.ni’,
‘.nl’, ‘.no’, ‘.np’, ‘.nr’, ‘.nu’, ‘.nz’, ‘.om’, ‘.pa’,
‘.pe’, ‘.pf’, ‘.pg’, ‘.ph’, ‘.pk’, ‘.pl’, ‘.pm’, ‘.pn’,
‘.pr’, ‘.ps’, ‘.pt’, ‘.pw’, ‘.py’, ‘.qa’, ‘.re’, ‘.ro’,
‘.ru’, ‘.rw’, ‘.sa’, ‘.sb’, ‘.sc’, ‘.sd’, ‘.se’, ‘.sg’,
‘.sh’, ‘.si’, ‘.sj’, ‘.sk’, ‘.sl’, ‘.sm’, ‘.sn’, ‘.so’,
‘.sr’, ‘.st’, ‘.sv’, ‘.sy’, ‘.sz’, ‘.tc’, ‘.td’, ‘.tf’,
‘.tg’, ‘.th’, ‘.tj’, ‘.tk’, ‘.tm’, ‘.tn’, ‘.to’, ‘.tp’,
‘.tr’, ‘.tt’, ‘.tv’, ‘.tw’, ‘.tz’, ‘.ua’, ‘.ug’, ‘.uk’,
‘.um’, ‘.us’, ‘.uy’, ‘.uz’, ‘.va’, ‘.vc’, ‘.ve’, ‘.vg’,
‘.vi’, ‘.vn’, ‘.vu’, ‘.wf’, ‘.ws’, ‘.ye’, ‘.yt’, ‘.yu’,
‘.za’, ‘.zm’, ‘.zw’
);

/* Four character domain names */
$dm2 = array(
‘.biz’,’.com’,’.edu’,’.gov’,’.int’,’.mil’,’.net’, ‘org’,
‘.pro’
);
/*Five character domain names */
$dm3 = array(‘aero’,’.coop’,’.info’,’.name’);

/*Finds string length and substrings */
$len = strlen($em);
$sub3 = substr($em,$len-3, $len);
$sub4 = substr($em,$len-4, $len);
$sub5 = substr($em,$len-5, $len);

/*Searches if the any of substrings match the listed domain
suffixes*/

$flag = false;
/* Searches if the three letter substring is valid*/
if( $flag != true )
{
for($i = 0; $i < count($dm1); $i++)
{
if($sub3 == $dm1[$i])
{
return true;
$flag = true;
break;
}
}
}
/* Searches if the four letter substring is valid*/
if( $flag != true )
{
for($j = 0; $j < count($dm2); $j++)
{

if($sub4 == $dm2[$j])
{
return true;
$flag = true;
break;
}
}
}
/* Searches if the five letter substring is valid*/

if( $flag != true )
{
for($k = 0; $k < count($dm3); $k++)
{
if( $sub5 == $dm3[$k])
{
return true;
$flag = true;
break;
}
}
}

/* Return false if none of substrings match the listed domain names*/
if( $flag == false)
{
return false;
}
};

[/code]

As you can see I have created three array containing TLDs and one more for the .museum would be created shortly. I know this seems foolish but the fact is I can’t use getmxrr or checkdnsrr because they won’t work on Windows servers.
Please suggest a shorter method perhaps using OOPs or by suggesting a solution to use any existing forms of getmxrr or checkdnsrr on Windows as well as UNIX servers. Also can use tell me of an existing open-source PHP class that checks for invalid characters and which invalid characters should be included while validating email ID’s and which while validating names, text-messages.

to post a comment
PHP

29 Comments(s)

Copy linkTweet thisAlerts:
@crh3675Jul 05.2005 — *redo*

You can access the Filesystem correct?

Try using the COM to do an NSLookup

[code]
<?

$objShell = new Com("WScript.Shell");
$objWshScriptExec = $objShell->Exec("nslookup -type=mx google.com");
$objStdOut = $objWshScriptExec->StdOut;
$strOutput = $objStdOut->ReadAll();

if(!strpos($strOutput,"MX preference")){
echo "Invalid email";
}else{
echo "Valid email.";
}


?>
Copy linkTweet thisAlerts:
@bokehJul 05.2005 —  I know this seems foolish but the fact is I can't use getmxrr or checkdnsrr because they won't work on Windows servers.
[/QUOTE]

If a function is missing you can often write it yourself. I am including an email validation script that checks with the remote mail server that it will accept mail for an email address. I have included my version of getmxrr() which runs on windows and emulates the PHP linux built in function. Let me know how you get on.
[code=php]
<?php
// For debug output add ?debug to the url for example
// http://www.domain.com/mailer.php?debug

//This function returns TRUE if the email validates and FALSE
//if it doesn't. It polls the remote mail server to see if it
//will accept mail on the address you are checking. By the way
//this does not check the email exists, but only that the remote
//mail server will accept the mail. Some mail servers accept
//mail for addresses that don't exist and then send a bounce
//or just put them in the bin without warning. It will work
//without getmxrr() as I have included this in the function.

function check_email_address_exists($email)
{

if (!function_exists('getmxrr')){
function getmxrr($hostname, &$mxhosts, &$weight = NULL)
{
$mxhosts = array();
exec('nslookup -type=mx '.$hostname, $result);
$result = implode("rn", $result);
preg_match_all("'^.*MX preference = (d{1,10}), mail exchanger = (.*)$'simU", $result, $mx_matches);
if (count($mx_matches[2]) > 0)
{
foreach($mx_matches[2] as $key => $value){
$mx_matches[2][$key] = trim($value);
}
array_multisort($mx_matches[1], $mx_matches[2]);
$mxhosts = $mx_matches[2];
if (!is_null($weight))
{
$weight = $mx_matches[1];
}
return True;
}
else
{
return False;
}
}
}



$result = true;

// Extract the mail server name from the email address.
list ($user, $domain) = split ("@", $email);
if (getmxrr($domain, $mxhost)){
$ConnectAddress = $mxhost[0];
}else{
$ConnectAddress = $domain;
}

// Try to open a socket at the mail server address.
$connect = fsockopen($ConnectAddress, 25);
if ($connect)
{

if (ereg("^220", $out = fgets($connect, 1024)))
{
while(ereg('220', $out)){
$debug[] = 'Remote: '.$out;
stream_set_timeout($connect, 0, 5000);
$out = fgets ( $connect, 1024 );
stream_set_timeout($connect, 5);
}
$debug[] = "Local: EHLO {$_SERVER['HTTP_HOST']}";
fputs ($connect, "EHLO {$_SERVER['HTTP_HOST']}rn");
$out = fgets ( $connect, 1024 );
while(!ereg('^250', $out)&&(!empty($out))){
$debug[] = 'Remote: '.$out;
stream_set_timeout($connect, 0, 5000);
$out = fgets ( $connect, 1024 );
stream_set_timeout($connect, 5);
}
for($tries = 10; $tries > 0; $tries--){
if(ereg('^250', $out)){
$debug[] = 'Remote: '.$out;
$for_loop_hop = $out;
}elseif(empty($out)){
usleep(100000);
}else{
$debug[] = 'Remote: '.$out;
}
stream_set_timeout($connect, 0, 5000);
$out = fgets($connect, 1024);
stream_set_timeout($connect, 5);
}
if(!ereg('^250', $for_loop_hop)){
$debug[] = 'No 250';
if(isset($_GET['debug'])){
foreach($debug as $line){
echo $line.'<br>';
}
}
return FALSE;
}
$debug[] = htmlspecialchars("Local: MAIL FROM: <mailer-daemon@{$_SERVER['HTTP_HOST']}>rn");
fputs ($connect, "MAIL FROM: <mailer-daemon@{$_SERVER['HTTP_HOST']}>rn");
$from = fgets ( $connect, 1024 );
$debug[] = 'Remote: '.$from;
$debug[] = htmlspecialchars("Local: RCPT TO: <{$email}>rn");
fputs ($connect, "RCPT TO: <{$email}>rn");
$to = fgets ($connect, 1024);
$debug[] = 'Remote: '.$to;
$debug[] = "Local: QUITrn";
fputs ($connect, "QUITrn");
$quit = fgets ($connect, 1024);
$debug[] = 'Remote: '.$quit;
fclose($connect);

// Validate our exchange with the mail server.

// Server rejected address.
if (!ereg ("^250", $from) || !ereg ("^250", $to))
{
$result = false;
}
}
// No response from server.
else
{
$result = false;
}
}
// Can't connect to server.
else
{
$result = false;
}
if($debug > 0){
foreach($debug as $line){
print "$line <br />rn";
}
}

return $result;
}

$email = '[email protected]';
$result = check_email_address_exists($email);

if($result){
echo $email.' validates';
}else{
echo $email.' does not validate';
}

?>


[/code]
Copy linkTweet thisAlerts:
@Jeff_MottJul 05.2005 — Bottom line is any kind of e-mail validation is not going to do you much good. I could put in [email][email protected][/email] or [email][email protected][/email]. Those addresses belong to somebody, I'm sure; just not me. And no matter how sophisticated the syntax checking and DNS lookup is it will never guarentee that the email I have put in is correct.
Copy linkTweet thisAlerts:
@bokehJul 05.2005 — Bottom line is no matter how sophisticated the syntax checking and DNS lookup is it will never guarentee that the email I have put in is correct.[/QUOTE]That's correct! Checking an email exist is not the same as checking it belongs to a particular user. The only way to know for certain is send an email containing a link to verify the user has access to that email. But this all depends on why you are checking the email. Whether you are checking for typos or liars.
Copy linkTweet thisAlerts:
@Jeff_MottJul 05.2005 — Whether you are checking for typos or liars[/quote]If it's typos, have a confirm email textbox, the same way you often have to enter a password two times. If it's checking for liars, well there's really nothing you can do about that.

Attempting to validate the email often results in bloated code and the rejection of a large set of valid addresses. You have to weigh the advantages against the disadvantages. Even a perfect validator still doesn't guarentee a correct address so there actually is no advantages.
Copy linkTweet thisAlerts:
@bokehJul 06.2005 — Attempting to validate the email often results in bloated code and the rejection of a large set of valid addresses.[/QUOTE]My script connects to the authorative mail server to see if it will accept mail for a particular address. If the authorative mail server rejects the address how can that rejection be false?

As for bloated code that is just a red herring since the code is executed on the server and therefore is irrelevant as far as the client is concerned.
Copy linkTweet thisAlerts:
@Jeff_MottJul 06.2005 — My script connects to the authorative mail server to see if it will accept mail for a particular address[/quote]Just because an AOL server accepts [email][email protected][/email] does not mean that this is my address.
Copy linkTweet thisAlerts:
@bokehJul 06.2005 — Just because an AOL server accepts [email][email protected][/email] does not mean that this is my address.[/QUOTE]That is irrelevant! My script is to check if the authoritive mail server will accept mail for a particular address, not to check who that address belongs to. If this is done in real time while the client is still in contact with the server the client can be informed of the problem before closing the connection. This operation does not need to slow things down and could even be done in the background using the xml_http_request_object allowing the client to be advised of any error before even submitting the form.
Copy linkTweet thisAlerts:
@pratik_learnerauthorJul 06.2005 — Well I equally agree with both the views of Jeff and bokeh are helpful but nevertheless I know of it already. What I actually wanted to know is how does one make a script secure. Can someone please highlight the common security pitfalls during the development of validation scripts.
Copy linkTweet thisAlerts:
@Jeff_MottJul 06.2005 — When using any kind of data you accept from the user you have to set a certain set of rules to make any kind of data safe for the application you plan to use it in. For example, if you are going to use user data on a Web page you need to escape HTML special characters (e.g, & < > " '); if you're going to use user data in an SQL statement then you need to escape characters such as " ' and (this varies between different databases so check the documentation for the one you're using). Or if you're using the data in a MIME message (that is, sending an email) then you need to make sure it obeys the rules of a MIME header (I went into more depth about this in another thread [url=http://www.webdeveloper.com/forum/showthread.php?t=66551][*][/url]).

So keeping your program safe from malicious users very much depends on how you will be using that data. You need to have a set of rules for safeguarding the data integrity for every specific application.

(Is this more the kind of information you were looking for?)
Copy linkTweet thisAlerts:
@bokehJul 06.2005 — The only way to make a server or website secure is to disconnect it from the internet, anything else is a comprimise. As far as PHP security goes the four most useful things I can think of that you can do are:

1) Turn off 'register globals'.

2) Turn off 'display errors'.

3) Set strict file permissions.

4) Check all submitted data is what it claims to be. For example a telephone number should only contain numbers. Or a name should only contain letters.

Lastly lots of people are flattering themselves thinking a hacker would be interested in their site. Why would the hacker bother. Your biggest worry is supplying a hacker with your clients credit card details. If your site doesn't contain this or other sensitive data why would a hacker be interested. If it is only to deface the site it would have to be high profile to be worthy of the effort.
Copy linkTweet thisAlerts:
@BeachSideJul 06.2005 — I don't know if you know/remember when PHPbb had an issue with a security breech in the pm system but I know of a couple of low profile forums that got messed with... it was actually kinda funny.
Copy linkTweet thisAlerts:
@pratik_learnerauthorJul 07.2005 — Bokeh whatever your perceptions security is much like spellings too close isn't enough. So as far as I am concerned I want to secure my site against immature vandals and not amateur crackers. So a low-profile security would be enough. Now that I'm gonna enter college I might be facing stiff security-concerns from my vandalous colleagues! Who knows who is who? But true bokeh low-profile sites do not generally face security issues. IF there are any it's mostly internal or due to some mass-virus/bug whatever!
Copy linkTweet thisAlerts:
@bokehJul 10.2005 — This operation does not need to slow things down and could even be done in the background using the xml_http_request_object allowing the client to be advised of any error before even submitting the form.[/QUOTE] I have thrown together a quick [URL=http://myhomewebserver.co.uk/validate_email_with_the_xml_http_request_object]example[/URL] of what I am talking about if you are interested!
Copy linkTweet thisAlerts:
@facJul 15.2005 — Bokeh,

Any chance you can post the script - with your permission I would like to use it on my site.

Thanks in advance,

Frank
Copy linkTweet thisAlerts:
@bokehJul 16.2005 — Bokeh,

Any chance you can post the script - with your permission I would like to use it on my site.

Thanks in advance,

Frank[/QUOTE]


Ok! But before I do you should know:

1) it is possibe there are bugs in this script (although it seems ok)

and

2) due to the nature of the way some mailservers are set up the script may gave some false positives. This is because it is only possible to check if the mail server with authority will accept email for a particular address and not that the address exists.

This script uses in part Javascript so in order to work that must be enabled at the clients browser so obviously for those without javascript and for security reasons data will need to be re-checked at the time of form submission maybe with a simple REGEX.

Also please bear in mind I just wrote this script for fun in the process of trying to get a better understanding of the XmlHttpRequest object.

I have grouped all the parts together into one, ready to run .php file which you should be able to run from anywhere on your server.

Let me know how you get on!

[code=php]<?php

// Validate an email
if(isset($_GET['checkEmail'])){
$email = trim($_GET['checkEmail']);
$regexp = '/^[^x00-x20()<>@,;:\".[]x7f-xff]+(?:.[^x00-x20()<>@,;:\".[]x7f-xff]+)*@[^x00-x20()<>@,;:\".[]x7f-xff]+(?:.[^x00-x20()<>@,;:\".[]x7f-xff]+)+$/i';
if (preg_match($regexp, $email)){
$valid = check_email_address_exists($email);
if($valid === FALSE){
$valid = 'invalid';
}elseif($valid === TRUE){
$valid = 'valid';
}
}else{
$valid = 'invalid';
}

header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."n".
"<response>n".
" <method>checkEmail</method>n".
" <result>$valid</result>n".
"</response>n";



// If not validating an email send the page
}else{

echo <<< PAGE


<html>
<head>

<script type="text/javascript">
/*<![CDATA[*/

function loadXMLDoc(url)
{
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send(null);
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send();
}
}
}

function processReqChange()
{
// only if req shows "complete"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// ...processing statements go here...
response = req.responseXML.documentElement;

method =
response.getElementsByTagName('method')[0].firstChild.data;

result =
response.getElementsByTagName('result')[0].firstChild.data;

eval(method + '('', result)');
}
}
}


function checkEmail(input, response)
{
if (response != ''){
// Response mode

if (response == 'invalid'){
document.getElementById("emailCheck").innerHTML = "<span class='red'><br />Warning: The email entered does not appear to be valid.<br /></span>";
}else{
document.getElementById("emailCheck").innerHTML = "<span class='green'><br />Email address appears to be OK.<br /></span>";
}
}else{
// Input mode
document.getElementById("emailCheck").innerHTML = "<span class='blue'><br />Checking email address...<br /></span>";
url =
'http://{$_SERVER['HTTP_HOST']}/{$_SERVER['PHP_SELF']}?checkEmail=' + input;
loadXMLDoc(url);
}

}

function clearSpan(){
document.getElementById("emailCheck").innerHTML = "";
}


/*]]>*/
</script>


<style type="text/css">
/*<![CDATA[*/

body {
font-size: 11pt;
font-family: verdana, sans-serif;
color: #000;
background:#fff;
text-align: center
}

.red {
color: red;
}

.green {
color: green;
}

.blue {
color: blue;
}

#first_paragraph {
width: 35%;
text-align: justify;
line-height: 1.5em;
margin: auto;
padding: 25px
}

input {
text-align: center;
width: 220px;
}

/*]]>*/
</style>

<title>Validating email with the XMLHttpRequest object</title>

</head>

<body>

<p id="first_paragraph">Example of email validation using the XmlHttpRequest object.
The email address is validated in real time as a background operation while the client
continues to fill out the form without any page reload. The email validation is conducted
by a PHP script which connects to and interogates the remote mail server. Give it a try.
Enter an email address in the first box then tab to the second box. In a real application
only the warning is necessary so if the email returns valid do nothing.</p>

Enter an email <input id="username" name="username" type="text"
onblur="checkEmail(this.value,'')" onfocus="clearSpan()" /><br />

<span id="emailCheck"></span><br />

Now tab here <input id="other" name="other" type="text" />

</body>
</html>

PAGE;


}


function check_email_address_exists($email)
{

if (!function_exists('getmxrr')){
function getmxrr($hostname, &$mxhosts, &$weight = NULL)
{
$mxhosts = array();
exec('nslookup -type=mx '.$hostname, $result);
$result = implode("rn", $result);
preg_match_all("'^.*MX preference = (d{1,10}), mail exchanger = (.*)$'simU", $result, $mx_matches);
if (count($mx_matches[2]) > 0)
{
foreach($mx_matches[2] as $key => $value){
$mx_matches[2][$key] = trim($value);
}
array_multisort($mx_matches[1], $mx_matches[2]);
$mxhosts = $mx_matches[2];
if (!is_null($weight))
{
$weight = $mx_matches[1];
}
return True;
}
else
{
return False;
}
}
}



$result = true;

// Extract the mail server name from the email address.
list ($user, $domain) = split ("@", $email);
if (getmxrr($domain, $mxhost)){
$ConnectAddress = $mxhost[0];
}else{
$ConnectAddress = $domain;
}
if(gethostbynamel($ConnectAddress) === FALSE){
return FALSE;
}

// Try to open a socket at the mail server address.
if($ConnectAddress == $domain){
$connect = @fsockopen($ConnectAddress, 25, $errno, $errstr, 5);
}else{
$tries = count($mxhost);
$i = 0;
$connect = @fsockopen($mxhost[$i], 25, $errno, $errstr, 5);
while(!$connect && !$tries == 0){
$i++;
$connect = @fsockopen($mxhost[$i], 25, $errno, $errstr, 5);
$tries--;

}
}

if ($connect)
{

if (ereg("^220", $out = fgets($connect, 1024)))
{
while(ereg('220', $out)){
$debug[] = 'Remote: '.$out;
stream_set_timeout($connect, 0, 5000);
$out = fgets ( $connect, 1024 );
stream_set_timeout($connect, 10);
}
$debug[] = "Local: EHLO {$_SERVER['HTTP_HOST']}";
fputs ($connect, "EHLO {$_SERVER['HTTP_HOST']}rn");
$out = fgets ( $connect, 1024 );
while(!ereg('^250', $out)&&(!empty($out))){
$debug[] = 'Remote: '.$out;
stream_set_timeout($connect, 0, 5000);
$out = fgets ( $connect, 1024 );
stream_set_timeout($connect, 10);
}
for($tries = 15; $tries > 0; $tries--){
if(ereg('^250', $out)){
$debug[] = 'Remote: '.$out;
$for_loop_hop = $out;
}elseif(empty($out)){
usleep(100000);
}else{
$debug[] = 'Remote: '.$out;
}
stream_set_timeout($connect, 0, 5000);
$out = fgets($connect, 1024);
stream_set_timeout($connect, 10);
}
if(!ereg('^250', $for_loop_hop)){
$debug[] = 'No 250';
if(isset($_GET['debug'])){
foreach($debug as $line){
echo $line.'<br>';
}
}
return FALSE;
}
$debug[] = htmlspecialchars("Local: MAIL FROM: <{$email}>rn");
fputs ($connect, "MAIL FROM: <{$email}>rn");
$from = fgets ( $connect, 1024 );
$debug[] = 'Remote: '.$from;
$debug[] = htmlspecialchars("Local: RCPT TO: <{$email}>rn");
fputs ($connect, "RCPT TO: <{$email}>rn");
$to = fgets ($connect, 1024);
$debug[] = 'Remote: '.$to;
$debug[] = "Local: QUITrn";
fputs ($connect, "QUITrn");
$quit = fgets ($connect, 1024);
$debug[] = 'Remote: '.$quit;
fclose($connect);

// Validate our exchange with the mail server.

// Server rejected address.
if (!ereg ("^250", $from) || !ereg ("^250", $to))
{
$result = false;
}
}
// No response from server.
else
{
$result = false;
}
}
// Can't connect to server.
else
{
$result = 'Failed to connect to remote mail server';
}
if(isset($_GET['debug'])){
if($debug > 0){
foreach($debug as $line){
print "$line <br />rn";
}
}
}

return $result;
}
?>
[/code]
Copy linkTweet thisAlerts:
@Jeff_MottJul 16.2005 — ^([_a-z0-9-]+)(.[_a-z0-9-]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*(.[a-z]{2,4})$[/quote]This bit here is going to guarentee that some perfectly valid addresses are rejected; all for the sake of still not actually knowing if the user typed in their correct address.
Copy linkTweet thisAlerts:
@bokehJul 16.2005 — OK, If anybody doesn't like my REGEX convert to the [B]Jeff Mott[/B] special:
[code=php]$regexp = '/^[^x00-x20()<>@,;:\".[]x7f-xff]+(?:.[^x00-x20()<>@,;:\".[]x7f-xff]+)*@[^x00-x20()<>@,;:\".[]x7f-xff]+(?:.[^x00-x20()<>@,;:\".[]x7f-xff]+)+$/i';
if (preg_match($regexp, $email)){[/code]


I hope I got that right because my brain is not powerful enough to process that much data all in one go.

By the way Jeff can you give me an example? I know now there are so 6 figure TLDs like .museum but is there anything else that would be stop.

By the way though, as I said above I just wrote this to aid my learning process so all constructive criticism is welcome.

[B]

Edit: Right Jeff! I've added that to the above script now! Anything else wrong? [/B]
Copy linkTweet thisAlerts:
@bokehJul 16.2005 — all for the sake of still not actually knowing if the user typed in their correct address.[/QUOTE] For that you would need to send an email and recieve a reply which is a lot different from just throwing a warning while a client is filling in a form. And the chances are even if you were to do that if the email was wrong I'm still 90% sure you would loose the client as they would just say I'm not going to deal with that website because they said they were going to email me but nothing arrived. As I said above all this script does is to check if the mail server with authority for an email address will in fact accept mail for it.
Copy linkTweet thisAlerts:
@Jeff_MottJul 17.2005 — By the way Jeff can you give me an example? I know now there are so 6 figure TLDs like .museum but is there anything else that would be stop.[/quote]All .travel TLDs would be rejected as well. And there is no way to know what other TLDs might be added in the future. Also, even though they are rarely seen, any of the following characters could legally be in an address ([font=courier new]!#$%&'*+^=?`{}|~[/font]). The actual definition says that it can be any ASCII character except for control characters, space, and specials (which are [font=courier new]()<>@,;:".[][/font])

In fact, my regexp that you found deviates from the specification slightly. Technically a domain name does not need any kind of top-level domain at all. For instance, [font=courier new]localhost[/font] is a valid domain name. However, people didn't like that the regexp let domains go without requiring a period, and since localhost was the only exception I knew of I decided to change it.

By the way though, as I said above I just wrote this to aid my learning process so all constructive criticism is welcome.[/quote]Learning is absolutely a good thing. And if you wanted to start a thread with your email validation script and ask for opinions, that's fine too. But you probably shouldn't be posting it as a product-ready solution for other people to copy until you've gone through that peer review process.

For that you would need to send an email and recieve a reply ... And the chances are even if you were to do that if the email was wrong I'm still 90% sure you would loose the client[/quote]Quite possibly. But the only way that would happen is if they had a typo in what they entered and didn't notice it; checking with the mail server won't always catch this either.

Checking with the mail server by itself is fine simply because there is no reason it should ever reject a valid address (being aware though that it still is no guarentee that the user entered correct information). Rejecting valid addresses is something you don't ever want to do because that really pisses people off when you tell them that the email they use everyday is not valid.
Copy linkTweet thisAlerts:
@BeachSideJul 17.2005 — First I must say that I think both Bokeh's script and Jeff Mott's reg ex are equally amazing. I use Jeff Mott's regex on just about every form that requires an email that I create (I have it in my snippet thing ? ) as for Bokeh's script I have no idea what it is doing with all that xsomethingourotherrequest.stuff but by golly I will find out!!! This is too good an opportunity to learn something new an interesting to just let it pass by me!.

Back to the question at hand...

pratik_learner's question
Bokeh whatever your perceptions security is much like spellings too close isn't enough. So as far as I am concerned I want to secure my site against immature vandals and not amateur crackers. So a low-profile security would be enough. Now that I'm gonna enter college I might be facing stiff security-concerns from my vandalous colleagues! Who knows who is who? But true bokeh low-profile sites do not generally face security issues. IF there are any it's mostly internal or due to some mass-virus/bug whatever![/QUOTE]
Really the best things you can do to avoid stupid people doing stupid things to your stuff is stuff like Jeff Mott's regex for email addresses, use these functions on a regular basis: addslashes(), strip_tags(), htmlspecialchars() or htmlentities, etc... I use strip_tags() alot and always use addslashes().
Copy linkTweet thisAlerts:
@NogDogJul 17.2005 — For what it's worth, here's the regexp I use:
[code=php]
# email address validation function
# kudos to http://iamcal.com/publish/articles/php/parsing_email/pdf/
function is_valid_email_address($email) {
$qtext = '[^\x0d\x22\x5c\x80-\xff]';
$dtext = '[^\x0d\x5b-\x5d\x80-\xff]';
$atom = '[^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c'.
'\x3e\x40\x5b-\x5d\x7f-\xff]+';
$quoted_pair = '\x5c\x00-\x7f';
$domain_literal = "\x5b($dtext|$quoted_pair)*\x5d";
$quoted_string = "\x22($qtext|$quoted_pair)*\x22";
$domain_ref = $atom;
$sub_domain = "($domain_ref|$domain_literal)";
$word = "($atom|$quoted_string)";
$domain = "$sub_domain(\x2e$sub_domain)*";
$local_part = "$word(\x2e$word)*";
$addr_spec = "$local_part\x40$domain";
return preg_match("!^$addr_spec$!", $email) ? 1 : 0;
}
[/code]
Copy linkTweet thisAlerts:
@BeachSideJul 17.2005 — Of course you would lol ?
Copy linkTweet thisAlerts:
@Jeff_MottJul 17.2005 — For what it's worth, here's the regexp I use:[/quote]Yup, that's a very good one as well. They derived their regexp from the same source I did.
Copy linkTweet thisAlerts:
@BeachSideJul 17.2005 — Yup, that's a very good one as well. They derived their regexp from the same source I did.[/QUOTE]
I'm stickin with yours Jeff Mott cause it scares me less, that beast up there is just frightening :eek:
Copy linkTweet thisAlerts:
@KravvitzJul 17.2005 — Yup, that's a very good one as well. They derived their regexp from the same source I did.[/QUOTE]
Could you please post a link to that source?

I'm not familiar with the .travel TLD. Where have you heard about it? It doesn't seem to be included in the 2005-04-29 version of [url=http://data.iana.org/TLD/tlds-alpha-by-domain.txt]this official list[/url].
Copy linkTweet thisAlerts:
@Jeff_MottJul 17.2005 — Could you please post a link to that source?[/quote]http://www.ietf.org/rfc/rfc822.txt

I'm not familiar with the .travel TLD. Where have you heard about it? It doesn't seem to be included in the 2005-04-29 version of this official list.[/quote]That's odd that it hasen't been included in the list yet. Here is the press release where .jobs and .travel were introduced.

http://www.icann.org/announcements/announcement-08apr05.htm
Copy linkTweet thisAlerts:
@towerboyJan 29.2006 — bokeh,

Why won't your script on post#3 work on my Unix server?
[CODE]Parse error: parse error, unexpected '=', expecting ')' in /var/www/html/test/mail.php on line 18[/CODE]
I didn't change a thing.
Copy linkTweet thisAlerts:
@bokehJan 29.2006 — [CODE]Parse error: parse error, unexpected '=', expecting ')' in /var/www/html/test/mail.php on line 18[/CODE][/QUOTE]That was my alpha code which [B]does[/B] run just fine on Windows (on my version antway). The problem is caused because in Windows setting a predefined value to a call by reference is allowed but on a Unix build it is not. Try changing that block to the following... or if it will only be used on Unix remove it completely.[code=php]<?



if (!function_exists('getmxrr')){
function getmxrr($hostname, &$mxhosts)
{
$mxhosts = array();
exec('nslookup -type=mx '.$hostname, $result);
$result = implode("rn", $result);
preg_match_all("'^.*MX preference = (d{1,10}), mail exchanger = (.*)$'simU", $result, $mx_matches);
if (count($mx_matches[2]) > 0) {
foreach($mx_matches[2] as $key => $value){
$mx_matches[2][$key] = trim($value);
}
array_multisort($mx_matches[1], $mx_matches[2]);
$mxhosts = $mx_matches[2];
return True;
}else{
return False;
}
}
} [/code]


[URL=http://bokehman.com/validate_email_with_the_xml_http_request_object.php]Here's an example of it in use.[/URL]
×

Success!

Help @pratik_learner spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...