You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术求助:在PHPMailer脚本中添加正则表达式防范垃圾邮件

Adding Spam Protection to Your PHPMailer Form

Hey there! Since you're a web designer new to PHP, I’ll break this down simply for you—let’s get that spam protection added to your form, and fix a small bug I noticed in your existing script too.

First, quick fix: You used $testo in your email body variable, but that should be $message (matching your POST field name). That was probably causing some unexpected behavior!

Now, let’s add regex-based spam checks step by step. We’ll validate three key areas to block most spam bots:

  • Valid email format
  • Legitimate name characters
  • Suspicious content in the message

Here’s the modified script with all protections added, plus comments to help you follow along:

<?php
require("class.phpmailer.php");

// First, clean up user input (basic security step)
$name = trim($_POST["firstName"]);
$email = trim($_POST["email"]);
$object = trim($_POST["oggetto"]);
$message = trim($_POST["message"]);

// --- SPAM PROTECTION START ---
// 1. Validate email format with regex (standard email pattern)
$emailRegex = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';
if (!preg_match($emailRegex, $email)) {
    echo "<script type='text/javascript'>alert('Invalid email format! Please enter a valid address.');</script>";
    echo "<script>setTimeout(\"location.href = 'index.html';\",1500);</script>";
    exit; // Stop script if validation fails
}

// 2. Validate name (allow letters, spaces, hyphens, apostrophes, and accented characters)
$nameRegex = '/^[a-zA-ZÀ-ÿ\s\'-]+$/u'; // Supports international names with accents
if (!preg_match($nameRegex, $name) || strlen($name) < 2) {
    echo "<script type='text/javascript'>alert('Invalid name! Please use only letters, spaces, hyphens, or apostrophes.');</script>";
    echo "<script>setTimeout(\"location.href = 'index.html';\",1500);</script>";
    exit;
}

// 3. Check message for common spam keywords
$spamKeywords = ['viagra', 'free money', 'click here', 'win now', 'promotion', 'loan', 'advertise'];
$messageLower = strtolower($message);
foreach ($spamKeywords as $keyword) {
    if (strpos($messageLower, $keyword) !== false) {
        echo "<script type='text/javascript'>alert('Your message contains suspicious content. Please try again.');</script>";
        echo "<script>setTimeout(\"location.href = 'index.html';\",1500);</script>";
        exit;
    }
}

// Optional: Block messages with too many links (a common spam red flag)
$linkCount = preg_match_all('/https?:\/\/|www\./', $message, $matches);
if ($linkCount > 2) {
    echo "<script type='text/javascript'>alert('Your message has too many links. Please reduce them and try again.');</script>";
    echo "<script>setTimeout(\"location.href = 'index.html';\",1500);</script>";
    exit;
}
// --- SPAM PROTECTION END ---

// Fix the $testo variable to $message and sanitize input to prevent XSS
$nomemittente = $name . ' ' . $email;
$messaggio = "<div style=\"font-family:Verdana, Arial, Helvetica, sans-serif; font-size: 14px; color: #000000;\"><br>
<strong>Nome:</strong> " . htmlspecialchars($name) . "<br>
<strong>Object:</strong> " . htmlspecialchars($object) . "<br>
<strong>E-mail:</strong> " . htmlspecialchars($email) . "<br><br>
<strong>Testo:</strong> " . htmlspecialchars($message) . "<br><br>
</div>";

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "xxx.xxxx.it";
$mail->SMTPAuth = true;
/*$mail->SMTPSecure = 'ssl';
$mail->Port = 465; */
$mail->Username = "xxxxxxxxx";
$mail->Password = "xxxxx";
$mail->SMTPDebug = 1;
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress("xxxxxxxxx@xx.com");
$mail->AddReplyTo($email, $name); // Fixed $nome to $name here too
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = "$nomemittente - Requested informations";
$mail->Body = $messaggio;

if($mail->Send()){
    echo "<script type='text/javascript'>alert('Message sent!')</script>";
    echo "<script>setTimeout(\"location.href = 'index.html';\",400);</script>";
}else{
    echo "<script type='text/javascript'>alert('Something goes wrong!')</script>";
    echo "<script>setTimeout(\"location.href = 'index.html';\",400);</script>";
}
?>

Quick Explanations for Your Reference:

  • Sanitization: I added htmlspecialchars() around all user input in the email body—this prevents cross-site scripting (XSS) attacks, a critical security step beyond spam protection.
  • Regex Patterns:
    • The email regex checks for standard formats like name@domain.com.
    • The name regex supports accented characters (so international users can submit valid names) while blocking weird symbols spam bots use.
    • The keyword list catches common spam phrases—you can add/remove terms from $spamKeywords based on the spam you receive.
  • Early Exits: Each validation check uses exit; to stop the script immediately if spam is detected, so the email never gets sent.

Why Your Previous Attempts Might Have Failed:

  • You might have added checks after the email was already prepared, so the script still sent the message even if validation failed. We placed checks at the top to stop processing early.
  • Or your regex patterns were too strict (blocking valid input) or too loose (missing spam). The patterns here are balanced for most common use cases.

内容的提问来源于stack exchange,提问作者Blizzard983

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:29:29