如何阻止表单在初次成功后多次发送电子邮件。

时间:2011-07-28 18:48:40

标签: php xhtml

有人可以告诉我示例代码或指明我做错了,因为下面的解决方案并没有给我带来太多好运:(
我正在使用一个联系表单,它使用jquery和php分别验证和发送电子邮件。表单工作正常,直到用户成功提交表单之后。一旦提交了表单,就会在同一页面上成功显示成功消息,但是,在页面发送时,页面会发送另一封电子邮件,因此,如果我进行无数次更新,我的邮箱中会收到无数邮件。

//handler.php
if(isset($_POST['submit'])) {
    if(!isset($hasError)) {
        $body = "Name: $name \n\nEmail: $email \n\nEnquiry: $enquiry";
        $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

        mail($emailTo, $subject, $body, $headers);
        $emailSent = true;
        header("location: ../about/?action=sent");
        exit();
}   

//index.php
var_dump($_GET);
<?php if(isset($hasError)) { ?> 
    <p class="error">Please make sure you have filled all fields with valid information. Thank you.</p>
<?php } ?>                        
<?php if(isset($emailSent) && $emailSent == true) { ?>
    <p><strong>Your enquiry was sent successfully.</strong></p>
    <p>Thank you for your enquiry! Your email was successfully sent and we will be in touch with you promptly.</p>
<?php }; ?>                       
<form id="contactform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <fieldset>
        <legend>Enquiry form</legend>
        <label for="name">Name:</label><input type="text" size="50" name="name" id="name" value="" class="required" />
        <label for="email">Email:</label><input type="text" size="50" name="email" id="email" value="" class="required email" />
        <label for="enquiry">Enquiry:</label><textarea rows="5" cols="20" name="enquiry" id="enquiry" class="required"></textarea>
        <input type="submit" name="submit" value="Submit enquiry" class="curved-btn"></input>
        <input type="hidden" id="form-id" name="form-id" value="general"></input>
    </fieldset>
</form>

非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:1)

您应该在此处使用post/redirect/get模式。

使用此模式主张从表单处理页面发送重定向作为响应,因此后续刷新不会多次触发这些操作。

来自文档:

  

...而不是直接返回网页,POST操作返回   重定向命令。

在伪代码中,您的处理程序页面应该具有以下内容:

  • 您拥有的初始处理代码
  • 发送电子邮件
  • 标题(“位置:/ someotherpage”);
  • 出口();

答案 1 :(得分:0)

发送电子邮件后,您需要正确重定向。多年来,我一直在使用以下代码作为实用程序类的一部分。不幸的是,它被复制并在网上多次重新发布,所以我不知道是谁创造了它。

// func: redirect($to,$code=307)
// spec: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
// 301 Moved Permanently - Forget the old page existed
// 302 Found - Use the same method (GET/POST) to request the specified page.
// 303 See Other - Use GET to request the specified page. Use this to redirct after a POST.
// 307 Temporary Redirect - Good for response to POST.
// redirect('/')
// redirect("/my/page")
// redirect("http://www.foo.bar/page.htm",303)
// redirect("./index.php",307)
public function redirect($to,$code=307) {
    $location = null;
    $sn = $_SERVER['SCRIPT_NAME'];
    $cp = dirname($sn);
    if (substr($to,0,4)=='http') $location = $to; // Absolute URL
    else {
        $schema = $_SERVER['SERVER_PORT']=='443'?'https':'http';
        $host = strlen($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:$_SERVER['SERVER_NAME'];
        if (substr($to,0,1)=='/') $location = "$schema://$host$to";
        elseif (substr($to,0,1)=='.') {
            $location = "$schema://$host/";
            $pu = parse_url($to);
            $cd = dirname($_SERVER['SCRIPT_FILENAME']).'/';
            $np = realpath($cd.$pu['path']);
            $np = str_replace($_SERVER['DOCUMENT_ROOT'],'',$np);
            $location.= $np;
            if ((isset($pu['query'])) && (strlen($pu['query'])>0)) $location.= '?'.$pu['query'];
        }
    }

    $hs = headers_sent();
    if ($hs==false) {
        if ($code==301) header("301 Moved Permanently HTTP/1.1"); // Convert to GET
        elseif ($code==302) header("302 Found HTTP/1.1"); // Conform re-POST
        elseif ($code==303) header("303 See Other HTTP/1.1"); // dont cache, always use GET
        elseif ($code==304) header("304 Not Modified HTTP/1.1"); // use cache
        elseif ($code==305) header("305 Use Proxy HTTP/1.1");
        elseif ($code==306) header("306 Not Used HTTP/1.1");
        elseif ($code==307) header("307 Temorary Redirect HTTP/1.1");
        else trigger_error("Unhandled redirect() HTTP Code: $code",E_USER_ERROR);
        header("Location: $location");
        header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
    }
    elseif (($hs==true) || ($code==302) || ($code==303)) {
        // todo: draw some javascript to redirect
        $cover_div_style = 'background-color: #ccc; height: 100%; left: 0px; position: absolute; top: 0px; width: 100%;';
        echo "<div style='$cover_div_style'>\n";
        $link_div_style = 'background-color: #fff; border: 2px solid #f00; left: 0px; margin: 5px; padding: 3px; ';
        $link_div_style.= 'position: absolute; text-align: center; top: 0px; width: 95%; z-index: 99;';
        echo "<div style='$link_div_style'>\n";
        echo "<p>Please See: <a href='$to'>".htmlspecialchars($location)."</a></p>\n";
        echo "</div>\n</div>\n";
    }
    exit(0);
}