停止通过PHP脚本发送表单提交垃圾邮件


Stop form submit spamming via PHP script

基本上,我有一个表单可以访问我制作的电子邮件脚本,并发送一条消息,其中包含用户在给定字段中设置的内容。我想知道是否可以通过PHP脚本禁止它多次提交。。。

这是一个电子邮件表单,所以如果用户多次按下"提交"按钮,它会多次发送电子邮件。如果一个人按下提交按钮100次,我的电子邮件将收到100条消息。

所以,我的问题是,一旦PHP脚本已经提交,有没有办法阻止它再次运行?

下面是表格的代码。

<form action="http://sebastianalsina.com/contact/sendmail.php" method="post">
    <input type="text" placeholder="Name" name="name">
    <input type="text" placeholder="Email" name="email">
    <input type="text" placeholder="Subject" name="subject">
    <textarea placeholder="Write your message here" name="message" rows="6"></textarea>
    <input type="submit" name="submit" class="sendmessage" value="Send message">
</form>

这是sendmail.php:

<?php
require 'PHPMailerAutoload.php';
include 'variables.php';
// receiver message
if ($_POST['name'] != "" && $_POST['email'] != "" && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && $_POST['message'] != "") {
    $mail = new PHPMailer;
    $mail->AddReplyTo($_POST['email'], $_POST['name']);
    $mail->setFrom($fromEmail, $_POST['name'] . ' (' . $companyName . ' Web Mailer)');
    $mail->addAddress($toEmail);
    $mail->isHTML(true);
    $mail->Subject = $_POST['subject'];
    $mail->Body = '**CODE WAS REMOVED HERE BECAUSE IT WAS REALLY LONG**';
    $mail->AltBody = $_POST['message'];
    if(!$mail->send()) {
        header("Location: error.php");
    } else {
        header("Location: thankyou.php");
    }
} else {
        header("Location: error.php");
}
?>

好吧,所以你的PHP和表单代码看起来不错。问题是用户在发送消息时没有被阻止点击该按钮。

处理此问题的一种方法是在单击按钮后禁用该按钮。这样,在页面重新加载之前只允许单击一次(您已经在PHP中使用重定向进行了重定向)

首先,你需要给你的表格一个ID:

<form id="message_form" action="http://sebastianalsina.com/contact/sendmail.php" method="post">

现在使用Javascript,以提供以下功能:

var form = document.getElementById("message_form");
form.addEventListener('submit', function () {
    form.submit.disabled = true;
});

希望这能有所帮助。