PHP发送重复的电子邮件

时间:2014-07-16 20:38:36

标签: php email

经过多次故障排除后,我相信我发现了问题。我们为我们的产品使用QR标签,当扫描QR码时,它会将用户带到运行此脚本的URL。如果我手动输入URL或者如果我使用我们的自定义QR扫描仪应用程序,那么用户将收到一封电子邮件。但是,如果我使用任何其他QR扫描应用程序,它将发送多个电子邮件。我怎样才能使这个脚本每次加载URL时只运行一次,即使它来自第三方应用程序?

<?php 

$queryString = $_SERVER['QUERY_STRING'];
$count=-6; 
$id=substr($queryString,$count,6); 

//db connection
$db = new mysqli('localhost', '*****', '*****', '*****');

if (mysqli_connect_errno()) {
    echo 'Error: Could not connect to database.  Please try again later.';
    exit;
}

$query = "SELECT * FROM `****` where id = '$id'";
$result = $db->query($query);
$row = $result->fetch_assoc();

$email = $row['email'];
$ownername = $row['ownername'];
$petname = $row['petname'];

//check to see if tag has been registered
if ($email != "") {

    //send email
    $datetime = date("D M j G:i:s T Y");
    $subject = "Alert";

    $mailheader.= "From: " . "Tag Team <support@tag.com>\n";
    $mailheader.= "X-Sender: " . "support@tag.com\n";
    $mailheader.= "Return-Path: " . "support@tag.com\n";
    $mailheader .= "Bcc: support@tag.com";

    $body .= "Dear " . $ownername . ", \n\n";

    $body .= "" . $petname . "'s Tag has just been scanned.\n\n";
    $body .= "Click here to Login :\n";
    $body .= "http://www.tag.com\n";
    $body .= "********************\n\n";
    $body .= "Regards,";
    $body .= " \n\n";
    $body .= "Tag Team";
    $body .= " \n\n";
    $body .= "Keeping Pets Safe and Found";

    mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");

    //end email alert
}

header("Location: http://www.smartphonepettag.com/id/profile.php?id=$id");
mysql_close($db);

?>

2 个答案:

答案 0 :(得分:0)

在代码段中,我看不出为什么你的脚本应该多次执行但与your post yesterday相关的任何原因,好像你邮件服务器上的某些东西出现了严重错误。

但无论如何,如果它不是邮件服务器错误,解决方案将是这样的:

// add this at the very first line
session_start();
// add this in the code
if($_SESSION['send'] != true){
  mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
  $_SESSION['send'] = true;
}

这将确保“mail()”函数永远不会为同一个用户执行两次。 您可以在PHP manual了解有关会话变量的更多信息。

答案 1 :(得分:0)

您可以在数据库中创建一个标志,指示电子邮件是否已发送。在发送电子邮件之前检查标志,在发送电子邮件后进行设置。