如何解决每次刷新页面时发送电子邮件的问题

时间:2018-12-20 06:07:39

标签: php forms sendmail

这些表单在提交后即可使用。但是刷新页面后,邮件会一次又一次地发送出去。

<?php
$to = "abc.com";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:mithlesh@rightturn.co.in \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
    echo "Message sent successfully...";
}else {
    echo "Message could not be sent...";
}
?>

4 个答案:

答案 0 :(得分:3)

有多种处理方法。

1)成功发送邮件后,请在下面编写代码。

if(!$retval->Send()) {
    header("Location: http://www.example.com");
    exit;
}

2)如果这不适用于您,请使用元刷新方法:

if(!$retval->Send()) {
    $to = "http://www.example.com";
    $url = $to;
    print "<meta HTTP-EQUIV=Refresh CONTENT=\"5; URL=$url\">";
    print "Thank you for your message.";
    exit;
}

3)您也可以使用cookie。 要使用cookie,您必须创建一个具有当前时间戳记值的令牌,并且每当您创建具有当前时间戳记的cookie时,然后在刷新页面时比较两个变量。但Cookie具有先前的时间戳,令牌具有当前的时间戳,则它将不匹配。

$token = time();
setcookie('formToken', $token, time() + 3600);

if(isset($_POST['submit'])){

    if($_POST['token'] != $_COOKIE['formToken']){
        // die("Sorry");

        $error_list .= '<li>You can not submit this form twice.</li>';

        echo $error_list;
        echo 'Thank you, your message has been sent. You do not need resubmit it again.';
        exit;

    }

Source

答案 1 :(得分:0)

您需要检查submit

if (isset($_POST['submit'])) {
}

所以您的代码是:

if (isset($_POST['submit'])) {
    $to = "abc.com";
    $subject = "This is subject";
    $message = "<b>This is HTML message.</b>";
    $message .= "<h1>This is headline.</h1>";
    $header = "From:mithlesh@rightturn.co.in \r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-type: text/html\r\n";
    $retval = mail ($to,$subject,$message,$header);
    if( $retval == true ) {
       echo "Message sent successfully...";
    }else {
       echo "Message could not be sent...";
    }
}

答案 2 :(得分:-1)

大多数邮件发送是在特定事件或活动之后发生的,就像提交表单或单击按钮一样。您需要设计具有相关字段的表单。然后您可以将isset()或!empty()用于$ _POST数组< / p>

if(!empty($_POST)){
    $to = "abc.com";
     $subject = "This is subject";
      $message = "<b>This is HTML message.</b>";
     $message .= "<h1>This is headline.</h1>";
     $header = "From:mithlesh@rightturn.co.in \r\n";
     $header .= "MIME-Version: 1.0\r\n";
     $header .= "Content-type: text/html\r\n";
     $retval = mail ($to,$subject,$message,$header);
     if( $retval == true ) {
        echo "Message sent successfully...";
     }else {
        echo "Message could not be sent...";
     }
}

答案 3 :(得分:-1)

将此代码放在isset提交按钮之外的php代码开头

if(empty($_SESSION['key']) && !isset($_SESSION['key'])){
  $randomkey = rand(0,99999);
  $mykey = $_SESSION['key'] = $randomkey
}

它为Session设置了唯一的随机密钥。现在在表单字段中有一个隐藏字段

<input type="hidden" name="key" value="<?=$mykey?>">

立即提交

第一个检查当前$mykey与隐藏变量匹配 执行某些操作后,未完成$mykey 因此,它可以防止用户通过刷新页面来多次添加数据。

我希望它可以帮助...:-)