-2

I made a little PHP script that checks if an email is valid. The only problem is that it doesn't check if the dot is BEHIND the '@'. It accept emails like this: Hi.Hello@hotmailcom when it should only accept emails like HiHello@hotmail.com

This is my script:

<?php
$mail = $_POST['mail'];

    function checkmail($mail)
        {
            if ((strpos ($mail, '@') !== false) && (strpos ($mail, ".") !==false))
            {                   
                return true;
            }
            else
            {
                return false;
            }
        }

if(checkmail($mail))    
{
echo"Goed"; 
}   
else    
{       
echo"Fout";     
}

?>

Thanks in advance!

skos
  • 4,102
  • 8
  • 36
  • 59
Gerlof Leuhof
  • 213
  • 1
  • 7
  • 18

3 Answers3

3

Don't badly reinvent the wheel, use filter_var('bob@example.com', FILTER_VALIDATE_EMAIL), or in your case better filter_input(INPUT_POST, 'mail', FILTER_VALIDATE_EMAIL).

http://php.net/filter_var
http://php.net/filter_input

deceze
  • 510,633
  • 85
  • 743
  • 889
1

As said in the above posts, you can use filter_var PHP function, BUT only if your PHP version is greater than 5.2.0. If you want some more generic email validation, you can also use regular expressions, see here and here for details.

Community
  • 1
  • 1
Bud Damyanov
  • 30,171
  • 6
  • 44
  • 52
1
if (
(strpos ($mail, '@') !== false) && 
(strpos ($mail, '@') == strrchr($mail, '@')) && 
(strripos($mail, ".") > strpos ($mail, '@'))
)
{return true;}

// explication:
//
// (strpos ($mail, '@') !== false) => '@' character is in the string
// (strpos ($mail, '@') == strrchr($mail, '@')) => '@' character is unique
// (strripos($mail, ".") > strpos ($mail, '@')) => last position of '.' character is      
// greater than '@' character position