Search code examples
phpemail-validationstrict

email validation 'Error : Strict Standards' or any best way to validate email?


I have a script that will validate an email address & I think this is the only solution to validate emails on form submission? I end up with this script

<?php
if(isset($_POST['email']))

{
    $email = $_POST['email'];  

    if (strpos($email, '@')) 
    {
        $first = end(explode("@", $email));

        if(checkdnsrr($first, 'MX')) 
        {
            $validate = 'Valid email.';
        }
        else 
        {
            $validate = 'Invalid email.';   
        }
    }
    else
    {
        $validate = 'Invalid email.';
    }

    echo $validate;
}
?>  
<form method="POST">
<input type="text" name="email">
<input type="submit" value="submit">
</form>

It runs correctly but I have this error Strict standards: Only variables should be passed by reference.

Is there any way to remove the ERROR? and IMPROVE the code? Is there any email validation so far that is really validate emails?


Solution

  • The reson is, end(explode("@", $email)); function causes the error, end() needs a reference, for that you can try using the below code,

    $EmailArray = explode("@", $email);
    $first = end($EmailArray);
    

    mixed end ( array &$array )

    end() advances array's internal pointer to the last element, and returns its value.

    Parameter:

    array: This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

    Return Values: Returns the value of the last element or FALSE for empty array.