我想使用 php 代码限制每小时发送电子邮件 90 封
最佳答案
您可以使用 PHP 以这种非常 hackish 的方式来完成此操作:
创建一个名为 count_offset.txt 的空白文件 这将是一个跟踪 90 个用户的分块集偏移量的文件。
创建另一个名为 count_emails.txt 的空白文件 这将是一个跟踪特定小时内发送的电子邮件数量的文件。
然后,运行电子邮件功能(通过 cron)的 PHP 脚本可以打开第一个文本文件来检查已发送哪个分块集,并将其发送给下一组用户。它可以检查第二个文件是否有 90 封电子邮件的限制。
例如:
$userCount = getNumberOfUsers(); // Whatever query you may have that counts how many total users there are.
$numChunks = ceil($userCount/90); // How many different groups to send the email.
$chunkFile = fopen('chunk_offset.txt', 'r+'); // Loads the file as resource.
$currentChunk = fread($chunkFile, filesize('chunk_offset.txt')); // Load the contents of chunk_offset.txt into variable.
$currentChunk = ($currentCount == '' ? 0 : (int)$currentChunk); // Load 0 if contents of file blank.
$countFile = fopen('count_emails.txt', 'r+'); // Loads the file as a resource in variable $countFile.
$currentCount = fread($countFile, filesize('count_emails.txt')); // Load the content of the file into variable $currentCount.
$currentCount = ($currentCount == '' ? 0 : (int)$currentCount); // If the value of $currentCount is blank, then sets it to integer 0, otherwise sets the variable as the integer value of file contents.
if ($currentCount <= 90) // Test the variable to see if it's under the limit. If it's under, send the email.
{
foreach ($whateverUserListYouHave as $integerKey => $emailAddress) // Iterating through whatever array of users you have.
// Hopefully index number => email, but the index number is important.
// Also, consistent ordering of the list of users is important.
// Remember, you can always create your own counter.
{
// The magic:
// You're testing for set of people who fall within the current chunk.
if ($integerKey >= ($currentChunk * 90) && $integerKey < ($currentChunk * 90 + 90))
{
send_email($emailAddress); // Whatever arbitrary email function you have here.
}
}
}
$currentCount++; // Iterate up the count.
fwrite($countFile, $currentCount); // Write the new count into the file.
if ($currentChunk == $numChunks) // If the current chunk number hits the total number of groups of 90, then reset the file to blank...
{
$currentChunk = '';
}
else if ($currentChunk < $numChunks) // ... Otherwise iterate up and let it hit the next chunk on the next hour.
{
$currentChunk++; // Iterate up the chunk.
}
fwrite($chunkFile, $currentChunk);
然后,编写另一个 cron,每小时清除 count_emails.txt 文件(或将内容变为 0)。这个另一个 cron 可以运行另一个 PHP 脚本,或者如果您愿意的话也可以是 Bash 命令。
如果您想使用 Bash 命令执行此操作,这将是 cron:
0 * * * * cat /dev/null > count_emails.txt
以上行添加到 cron 时,使用 cat 清除 count_emails.txt 文件的内容。
干杯,祝你好运!
关于php - 如何使用php代码限制每小时发送电子邮件90封?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11372626/