Search code examples
phpformsemailauthenticationverification

How to check for an @ in an email address from a form post


I have a form with login and registration.

My Form

<form method="POST" action="login.php">
    <input type="text" name="mail" value="Input your email"/>
    <input type="submit" value="Check"/>
</form>

If someone enters their email, I want to check if there is an @ in the address. I have tried using an array, but that is not working.


Solution

  • You can use the php function strpos http://php.net/strpos

    if(strpos($myEmailPostVariable, '@') === FALSE) {
        // do things here to say it failed
    }
    

    If you are fixed on using an array then you could use explode http://php.net/explode

    $parts = explode('@', $myEmailPostVariable);
    if(count($parts) != 2) {
        // do things here to say it failed
    }
    

    Keep in mind the array way is not great as searching a string is easier and faster and is more readable.

    As @jeroen has suggested if you want to validate the email then using filter_input() is the best...

    if(filter_input(INPUT_POST, 'mail', FILTER_VALIDATE_EMAIL) === FALSE) {
        // do things here to say it failed
    }