Vérifier une adresse email
<?php
function emailOK ($email)
{
// Check if the given email is correct
// return TRUE si email is OK
// return FALSE if it is BAD
if (strspn($email, "0123456789abcdefghijklmnopqrstuvwxyz".
"ABCDEFGHIJKLMNOPQRSTUVWXYZ.-@")!=strlen($email))
return FALSE; // Bad caracters
if (strlen($email)>255)
return FALSE; // Too long
list($login,$domain,$bad)=explode("@", $email);
if (empty($login)) return FALSE; // No login
if (empty($domain)) return FALSE; // No domain
if (!empty($bad)) return FALSE; // Multiple @
if ($domain[0]==".") return FALSE; // @. forbidden
$domain=strrev($domain);
$arr=explode(".", $domain);
$tld=$arr[0];
if (empty($tld)) return FALSE; // No TLD
if (strlen($tld)<2 || strlen($tld)>4) return FALSE;// TLD too short/big
if (!isset($arr[1])) return FALSE; // Just a TLD
foreach ($arr as $key=>$dom)
{
// TLD check before
if ($key==0) continue;
if (empty($dom)) return FALSE; // No local domains
// or ..
if (strlen($dom)<2) return FALSE; // local domain short
}
return TRUE;
}
?>
Retourne FALSE pour tous les mails sauf les deux derniers de la liste ci-dessous :
<?php
echo "RC=".emailOK ("toto")."\n";
echo "RC=".emailOK ("toto@")."\n";
echo "RC=".emailOK ("@toto")."\n";
echo "RC=".emailOK ("i@toto")."\n";
echo "RC=".emailOK ("i@toto.")."\n";
echo "RC=".emailOK ("i@.toto.fr")."\n";
echo "RC=".emailOK ("i@to@to.kk")."\n";
echo "RC=".emailOK ("i@toto.j")."\n";
echo "RC=".emailOK ("i@tod..to.jj")."\n";
echo "RC=".emailOK ("i@toto.jrooo")."\n";
echo "RC=".emailOK ("i@to.jro")."\n";
echo "RC=".emailOK ("i@toto.jroo")."\n";
echo "RC=".emailOK ("i@toto.jr")."\n";
echo "RC=".emailOK ("i@tod.to.jj")."\n";
?>