Reputation: 9289
I am working on a comment form for a website and trying to secure against spammers. I have taken the validEmail function from this link.
I am not very experienced at using functions. Is this the proper way to call the function and validate the user's email address? Any suggestions appreciated. Thank you
$email = $_POST['email'];
if (validEmail($email)) {
$to = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: [email protected]';
mail($to, $subject, $message, $headers);
print "Form submitted successfully: <br>Your name is <b>".$_POST['cname']."</b> and your email is <b>".$_POST['email']."</b><br>";
} else {
print "There was an error with your form submission.";
}
Upvotes: 0
Views: 1802
Reputation: 18937
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "e-Mail is Valid";
} else {
echo "Invalid e-Mail";
}
Upvotes: 0
Reputation: 9860
That whole linked validEmail()
function can be replaced with:
function validEmail($email)
{
if (filter_var('[email protected]', FILTER_VALIDATE_EMAIL) !== false) {
$domain = preg_split("/@/", $email);
$domain = $domain[count($domain) - 1];
if (checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")) {
return true;
}
}
return false;
}
though I'm just taking the checkdnsrr()
function from the article you linked. I'm not familiar with it and I haven't used it for anything before. The built-in filter_var()
function is probably all you really would want to use, as checking DNS takes time (so every time someone submits something to your form, your script would possibly do 2 DNS lookups).
Upvotes: 1
Reputation: 11820
The function containing validEmail( $email );
should be included into you file:
include "whatever.php"
(Or, you could copy and paste the function into the same file as your code)
Your if
statement should look something like this:
if( validEmail( $email ) ) {
// print your success message here
} else {
// print your fail message here
}
In answer to your comment below, you can also write the above like this:
if( validEmail( $email ) === true ) {
// print your success message here
} else {
// print your fail message here
}
Upvotes: 1
Reputation: 4310
PHP has, since 5.2.0, its own validation filters that can be used to check whether the user has entered a proper e-mail address. There is no need to rely on things that you find on the internet for that purpose, since these functions can be flawed or broken. To use filter_var() for e-mail validation, the solution would be:
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
print "E-mail is correct";
} else {
print "E-mail is not correct";
}
(also note that your original example code in the question had a missing semi-colon in one of the prints).
Upvotes: 3