<?php

/*
 * Check Email string for validity
 * Paul Gregg <pgregg@pgregg.com>
 * January 2002, Updated Nov 2003, Logic fix May 2006
 * http://www.pgregg.com/projects/php/code/validate_email.inc.phps
 * Copyright 2002-2003, Paul Gregg.
 */

Function ValidateEmail($emailstr) {
    
// Make the email address lower case and remove whitespace
    
$emailstr strtolower(trim($emailstr));
    
    
// Split it up into before and after the @ symbol
    
$email_components explode('@'$emailstr);
    
    
// Check that there is only one @ symbol
    
if (count($email_components) != 2)
        return 
FALSE;
    
    
// Check that the username is >= 1 char
    
if (strlen($email_components[0]) == 0)
        return 
FALSE;
    
    
// Split the domain part into the dotted parts
    
$domain_components explode('.'$email_components[1]);
    
    
// check there are at least 2
    
if (count($domain_components) < 2)
        return 
FALSE;
    
    
// Check each domain part to ensure it doesn't start or end with a bad char
    
foreach ($domain_components as $domain_component)
      if ( 
strlen($domain_component) > ) {
        if ( 
preg_match('/[\.-]/'$domain_component[0])
          || 
preg_match('/[\.-]/'$domain_component[strlen($domain_component)-1]) )
          return 
FALSE;
      } else
        return 
FALSE;


    
// Check the last domain component has 2-6 chars (.uk to .museum)
    
$domain_last array_pop($domain_components);
    if (
strlen($domain_last) < || strlen($domain_last) > 6)
        return 
FALSE;
    
    
// Check for valid chars - Domains can only have A-Z, 0-9, ., and the - chars,
    // or be in the form [123.123.123.123]
    
if ( preg_match('/^\[(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\]$/'$email_components[1], $ipnum) )
        return (
ip2long($ipnum[1]) === false false true);

    if ( 
preg_match('/^[a-z0-9\.-]+$/'$email_components[1]) )
        return 
TRUE;

    
// If we get here then it didn't pass
    
return FALSE;
}
?>