PHP cronjob自动提醒邮件


php cronjob auto reminder email

我建立了一个web应用程序,其中用户支付了1/3/6个月并加入了网站,我需要在他的帐户到期前15天向用户发送提醒邮件,我如何才能实现它?我没有理解正确的逻辑…我在数据库中存储注册日期,过期日期,下面的逻辑工作正常吗?

<?php
$expiringDate = "2015-07-21";
$todaydate = date("Y-m-d");
$date = date("Y-m-d",strtotime("-15 days", strtotime($expiringDate)));
if($todaydate == $date){
//send mail
}else{
//quit
}?>

,我也想改变一个值在数据库中,如果今天是过期日…是在其他cronjob中更好还是我可以在上面的代码中这样做…

 <?php
$expiringDate = "2015-07-21";
$todaydate = date("Y-m-d");
$date = date("Y-m-d",strtotime("-15 days", strtotime($expiringDate)));
if($todaydate == $date){
//send mail
}else{
//check and change the value if today is the expiring
    }?>

我走在正确的道路上吗?这是安全的吗?还是有其他更好的方法来完成这项工作

我建议每天运行cron作业。

你的PHP脚本应该检查所有在15天内过期的人。

然而,正如其他人指出的,如果有一天你的cron工作失败了,你可能会错过一批人。

因此,我会检查剩下15天或少于的人,这些人在数据库中没有针对他们设置提醒标志。这意味着如果cron作业失败的人还有15天的剩余时间,那么在14/13/12等剩余的日子里,你的脚本将看到提醒标志没有针对他们设置,并且仍然会发送提醒。

<?php
$reminderSent = false; // Get this value from the db (true or false)
$expiryActioned = false; // Get this value from the db (true or false)
$expiringDate = strtotime('2015-07-21'); // Get this date from the db
$todayDate = time();
$reminderDate = strtotime("-15 days", $expiringDate);
if ($todayDate >= $reminderDate && $reminderSent == false) {
    // Send mail
    // Set flag $reminderSent in database to indicate reminder has been sent
} elseif ($todayDate >= $expiringDate && $expiryActioned == false) {
    // Do something
    // Set $expiryActioned in database to indicate the user has expired and something has been done about it
}
?>

但是,与其选择每个人并使用上述逻辑运行它们,不如将上述逻辑构建到您的SQL查询中以获得更好的效率。

快速的例子:

// Select all users that expire in 15 days or less
SELECT `userid`, `name`, `email` FROM `user` WHERE NOW() >= DATE_SUB(`expiry`, INTERVAL 15 DAY) AND reminder_sent = 0
// Now loop through each user, send them an email and then:
UPDATE `user` SET reminder_sent = 1 WHERE `userid` = X

// Select all users that have expired
SELECT `userid`, `name`, `email` FROM `user` WHERE NOW() >= `expiry` AND `expiry_actioned` = 0
// Now loop through each user, do whatever you need to and then:
UPDATE `user` SET expiry_actioned = 1 WHERE `userid` = X