所以基本上,我有一个可以进行一些计算的表格。
提交此表格后,它将通过电子邮件将所有信息发送给我。
虽然,有些用户喜欢做一些计算,直到他们做对为止。例如,他们会多次提交表单。因此,我不想收到所有这些电子邮件,只收到第一封。
有什么方法可以在他们第一次提交表单时创建一个 cookie,以便只通过电子邮件发送一次?
当然
if(!isset($_COOKIE['mailsent'])) {
// send mail!
setcookie('mailsent');
}
您可以使用 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"
}
?>
希望能帮助到你