每当客户进入特定页面时,我都可以通过发送电子邮件来使我的代码工作,问题是如果用户/客户重新加载页面,则会发送一封新电子邮件,这可能导致数百封邮件从我的 smtp 服务器。
我正在寻找一种简单的替代方案,它只能每 5/10/15 分钟发送一次验证电子邮件。不是在用户重新加载页面时。
我应该使用 javascript 还是对该函数进行简单的 sleep 操作。
PD:通过 php 上的 $_SESSION
变量发送电子邮件。
答案 0 :(得分:0)
您可以为此使用 cron 作业(如果您的托管环境允许您定义一个),或者跟踪您自己上次发送电子邮件的时间。
在后一种情况下,您可以例如:
/**
* Get the current date & time.
*
* @return String
*/
function now() {
return date('Y-m-d H:i:s');
}
/**
* Store last send date. For the sake of simplicity, let's
* write it to a file.
*
* @return String
*/
function last_send_update($date) {
file_put_contents('mails_last_send.json', json_encode(['date' => $date]));
}
/**
* Get last send date from a file.
*
* @return String
*/
function last_send_get() {
if (!file_exists('mails_last_send.json')) {
last_send_update(now());
}
return json_decode(file_get_contents('mails_last_send.json'))->date;
}
/**
* Mock sending mails.
*/
function send_mails() {}
// Do the actual math & decide what to do.
$last_send = date_create(last_send_get());
$now = date_create(now());
$diff = date_diff($now, $last_send)->i; // Difference in minutes
if ($diff >= 10) {
send_mails();
last_send_update($now);
}
有关 Cron 及其使用方法,请参阅: