PHP:即使未填写表格,也可以发送电子邮件的联系表格


PHP: Contact form sending e-Mail even when forms not filled?

我已经在网站上工作了一段时间,我的联系表格一直遇到这个问题。

所以我确保我在联系表格上包括"必需",如果没有填写表格,那就太好了。它确保用户将信息放入要发送的信息的字段中。

但是,在iOS上并非如此。这些必需的标签被忽略了,所以我构建了我的 PHP 以确保仍然需要输入。

希望有人可以帮助我。

这是 HTML 联系表单:

        <input type="text" name="phone" class="phoneInput" autocomplete="off" placeholder="What phone number can we reach you at? (Optional)" /><br />
        <input type="email" name="email" class="emailInput" autocomplete="off" placeholder="What is your primary e-mail address?" required /><br />
        <textarea name="message" id="message" autocomplete="off" placeholder="How may we assist you?" required></textarea><br />
        <div class="submit">
            <input type="submit" value="SEND MESSAGE" id="button"/>
            <div class="ease"></div>
        </div>
    </form>

更新的 PHP:

<?php
// Name of sender
$name=$_GET["name"];
// Phone number of sender
$number=$_GET["phone"]; 
// Mail of sender
$mail_from=$_GET["email"];
// Message
$message=$_GET["message"];
// Subject 
$subject= "Someone has sent you a message from your contact form!";
// Message Headers
$headers = 'From: ' .$name."'r'n". 'Reply-To: ' . $mail_from."'r'n" . 'Callback Number: '.$number."'r'n";
// E-mail to:
$to ='shawn@synergycomposites.net';
// Empty variables, tests to see if any of the fields are empty
$emptyName    = empty($name);
$emptyEmail   = empty($mail_from);
$emptyMessage = empty($message);
// Perform if tests to see if any of the fields are empty, and redirect accordingly
if ($emptyName == true) {
    header ("location:/#modalFailure");
} else {
    if ($emptyEmail == true) {
        header ("location:/#modalFailure");
    } else {
        if ($emptyMessage == true) {
            header ("location:/#modalFailure");
        } else {
            header ("location:/#modalSuccess");
            mail($to, $subject ,$message, $headers);
        }
    }
}
?>

在检查字段之前调用 mail() 函数。此函数实际上发送电子邮件。返回变量 $send_contact 只是一个布尔值,无论函数是否成功。这样的事情应该有效:

if(empty($name) || empty($mail_from) || empty($message)) {
  header('location:/#modalFailure');
} else {
  $mail_sent = mail($to, $subject ,$message, $headers);
  if(!$mail_sent) {
    header("location:/#modalFailure");
  } else {
    header("location:/#modalSuccess");
  }
}

如果表单提交非空字符串,则此代码将遇到问题。例如,这" "而不是""NULL。还建议在此代码中添加筛选和验证。

(另一方面,您可能希望使用 $_POST 而不是 $_GET 来提交表单。

相关文章: