I am trying to make a form that is secure from spam and sends a simple email to the person who registers.
Im quite new to PHP and the problem im faced with is when the form is submitted with a false email address in the email field, it brings up the error message stating that the email is invalid, but still lets the registration go through adding it to the database.
here is the code
function spamcheck($field) {
// filter_var() sanitizes the e-mail
// address using FILTER_SANITIZE_EMAIL
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
// filter_var() validates the e-mail
// address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
}
else {
return FALSE;
}
}
if(isset($_REQUEST['email'])) {
// if "email" is filled out, proceed
// check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE) {
die("<font color='red'>Your email address is invalid, please try again.</font><br/><br/><form><INPUT TYPE='button' VALUE='Back' onClick='history.go(-1);return true;'></form>");
}
else {//send email
$to = "$email";
$from = "name@mywebsite.com";
$message = "Just a message";
$subject = "Subject";
mail($to, $message, $subject, "From: $from", "-f$from");
}
}
Any help would be greatly appreciated.
Maybe the problem here is, that your check-function first sanitizes the email address, and afterwards validates the sanitized email. That means, the check-function checks the sanitized email, but outside of the function you are still working with the invalid email.
So either do the sanitizing outside of the check function, or in my opinion even better, only validate the input without sanitization (better to make the user aware that he typed it incorrect, than trying to repair it).
Edit:
Actually there must be another problem, because when the code
die(...Your email address is invalid...)is executed, the processing of the page stops. We would need to see the part of the code, which writes to the database.