Use captchas to prevent spam bots from abusing your contact form and to ensure that only human beings can use it.
How to block spam mails in inbox using php
-
04-06-2022 - |
Question
I have coded a contact us form and its process page for one of my client in php
When a user submits the form a mail is generated and its redirected to my clients inbox
Here im getting a terrible hundreds of unknown spam mails at the end of the day, i don't know where it is generating from,
Due to this our website is in danger from being added in blacklist on google and other search engines
Can anyone please give me a solution to block this spam mails and also please find the attachment for my php mail code
Below is my php code
<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$email = $_POST["email"];
$to = "test@myaddress.com";
$cname = htmlentities(ucfirst($_POST['name']));
$subject = "Subject Comes here";
$body= "Name : ";
$body.= $cname;
$body .= "\nE-mail : ";
$body .= htmlentities($_POST['email']);
$body.= "\nMessage : ";
$body.= htmlentities($_POST['message']);
function is_valid_email($email)
{
return preg_match('#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$#si', $email);
}
function contains_bad_str($str_to_test) {
$bad_strings = array(
"content-type:"
,"mime-version:"
,"multipart/mixed"
,"Content-Transfer-Encoding:"
,"bcc:"
,"cc:"
,"to:"
);
foreach($bad_strings as $bad_string) {
if(eregi($bad_string, strtolower($str_to_test))) {
header('Location: status.php?status=failed');
}
}
}
function contains_newlines($str_to_test) {
if(preg_match("/(%0A|%0D|\\n+|\\r+)/i", $str_to_test) != 0) {
header('Location: status.php?status=failed');
}
}
if (!is_valid_email($email)) {
header('Location: status.php?status=failed');
}
contains_bad_str($email);
contains_bad_str($subject);
contains_bad_str(body);
contains_newlines($email);
contains_newlines($subject);
$headers = "From: $email";
mail($to, $subject, $body, $headers);
header('Location: status.php?status=success');
}
?>
Solution 2
OTHER TIPS
Or use a hidden field that should stay empty. Spambots have the habit of filling all the input fields.
More about this here: How to prevent robots from automatically filling up a form?