简体   繁体   English

php mail()发送两个副本

[英]php mail() two copies sent

I have a simple message that I send using php mail(). 我有一条使用php mail()发送的简单消息。 The code used: 使用的代码:

//recipient info
$to = "$bookernavn <$mail>";
$from = "Visens Venner Hillerød <booking@eksample.dk>";
$subject = "Kvittering - $a_titel - ". date("j/n - Y",$a_dato);

$headers  = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=utf-8" . "\r\n";
$headers .= "From: $from" . "\r\n";
$headers .= "Reply-To: $from" . "\r\n";
$headers .= "Return-Path: $from" . "\r\n";
$headers .= "Bcc: $from" . "\r\n";

// now lets send the email. 
mail($to, $subject, $mailmsg, $headers); }

For some strange reason two mails are sent each time... 由于某些奇怪的原因,每次都会发送两封邮件...
Sometimes with several minutes in between... 有时在几分钟之间...
Any ideas? 有任何想法吗?

You don't check to see if the form has been submitted so a browser refresh will send the form data again and cause the mail to be sent again. 您无需检查表单是否已提交,因此浏览器刷新将再次发送表单数据并导致再次发送邮件。 This also happens when a user presses the back button. 当用户按下“后退”按钮时,也会发生这种情况。

After the email is sent you need to do a 303 redirect to prevent the re-submission. 发送电子邮件后,您需要执行303重定向以防止重新提交。 You can redirect to the same page if you'd like. 您可以根据需要重定向到同一页面。

This is called the Post/Redirect/Get pattern . 这称为Post / Redirect / Get模式

mail(...);
header('Location: /some-page-php', true, 303);
exit;

an easy way to prevent this from happening is to use POST method instead of GET for the form. 防止这种情况发生的一种简单方法是对表单使用POST方法而不是GET。

<form method="post">



if (isset($_POST['submitted']))

and at the end of the mail code use a redirect that will send the browser to load using a GET method. 并在邮件代码的末尾使用重定向,该重定向将使浏览器使用GET方法进行加载。

Not only you can then redirect your user to a OK page "mail was sent" or a error page "sorry there was a mistake, please try again", a refresh of that page open by the browser will only send a GET, not triggering the send mail function 然后,您不仅可以将用户重定向到“发送邮件”的“确定”页面或“对不起,请重试”错误页面,而且浏览器打开该页面的刷新将仅发送GET,而不触发发送邮件功能

if (empty($errors)) {
  header('Location: http://www.example.com/mail_OK.html');
  exit;
} else {
  // passing data to the "error/retry" page
  $info = array(
    'msg' => $msg,
    'email' => $_POST['email'],
    'name' => $_POST['name']
    // etc...
  )
  header('Location: http://www.example.com/mailform.php?'.http_build_query($info));
  exit;
}

in your form you can retrieve those info 在您的表格中,您可以检索这些信息

<input name="name" type="text" placeholder="Naam" class="form-control" value="<?php echo htmlspecialchars($_GET['name']); ?>">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM