【问题标题】:How to only send an email once on form submit by creating a cookie?如何通过创建 cookie 在表单提交时只发送一次电子邮件?
【发布时间】:2013-10-30 09:54:26
【问题描述】:

所以基本上,我有一个可以进行一些计算的表格。

提交此表格后,它将通过电子邮件将所有信息发送给我。

虽然,有些用户喜欢做一些计算,直到正确为止。例如,他们会多次提交表单。因此,我不想收到所有这些电子邮件,只收到第一封。

有什么方法可以在他们第一次提交表单时创建一个 cookie,以便只通过电子邮件发送一次?

【问题讨论】:

  • 能否详细说明some users like to do a few calculations until they get it right.
  • @LawrenceCherone - 抱歉,刚刚修好了。

标签: php forms cookies


【解决方案1】:

当然

if(!isset($_COOKIE['mailsent'])) {
   // send mail!
   setcookie('mailsent');
}

【讨论】:

  • 太容易了!感谢您的帮助:)
【解决方案2】:

您可以使用 cookie,但更好的方法是使用会话存储如果用户已经发布了您的表单,因为 cookie 可以更改、删除甚至永远不会在用户计算机上设置,非常容易绕过任何您要实施的保护。任何形式都必须添加基本的 csrf 保护。

<?php 
session_start();

if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['your_vals_ect'])){
    //check csrf
    if(isset($_SESSION['csrf'], $_POST['csrf']) && $_SESSION['csrf']==$_POST['csrf']){

        if(isset($_SESSION['mail_sent'])){
            //notify the user that they can only submit once or redirect somewhere
        }else{
            //send mail
            mail(...);
            //set the session var
            $_SESSION['mail_sent'] = true;

            //send the user somewhere after or refresh the page to clear the $_POST
            exit(header('Location: '.$_SERVER['REQUEST_URI']));
        }

    }else{
        //notify user that form must be loaded from site
    }

}else{
    //set a csrf token so user cant post from another site or custom form/request.
    $_SESSION['csrf'] = sha1(uniqid(true));

    //show your form code ect
    //use $_SESSION['csrf'] within a hidden field name="csrf"
}
?>

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多