Hi everyone,
I have a problem, as well as a potential solution, but as I'm not what I would call an experienced PHP programmer I was hoping I could borrow your wisdom to see if what I've come up with is worthwhile.
My problem is that my server was timing out when sending 2000+ emails. As each email is based on personal settings inputted by the subscriber I can't use the BCC option so I have to send them one by one.
My original stab at finding a solution was to try processing the emails in batches of 100, with a 1 minute rest for the server to catch up inbetween, but that didn't work.
The next thing I did was increase the TimeOut variable in my apache config file, which worked, but I can see that this is only a temporary solution, as my list will only continue to grow.
So I started thinking... what if I processed X number of batches (of 100 emails) and then called the script again using header("Location: ""); passing the necessary variables of course, to process the next X number of batches, and so on, and so on.
I put together the following code that appears to be working, but as I said in the beginning I'm not sure if it is functionally sound as a long term solution so I was hoping you could take a look and give me your opinion. My concern (although I don't know if it should be a concern) is calling the script over and over. Am I opening myself up to problems? Or perhaps, is there a better solution?
<? php
require_once('local.config.inc.php');
// set number of emails to process at one time
$limit = '100';
// set number of batches to rotate
$rotate = '5';
// grab start var from URL, if not there set $start = 0
$start = ($_GET['start']) ? $_GET['start'] : '0';
// grab end var from URL, if not there set $end = $limit
$end = ($_GET['end']) ? $_GET['end'] : $limit;
// grab batch var from URL, if not there set $batch = 1
$batch = ($_GET['batch']) ? $_GET['batch'] : '1';
// Determine number of emails to process today
$sel = "SELECT * FROM maillist WHERE unsub='0' ORDER BY id";
$res = mysql_query("$sel");
$num_rows = mysql_num_rows($res);
// start while loop to process emails in batchs
while ($num_rows > ($end - $limit)) {
$batch++; // increment batch by 1 for each pass through while loop
// select emails to process for this batch
$selstr = "SELECT * FROM maillist WHERE unsub = '0' ORDER BY id LIMIT $start,$end";
$result = mysql_query("$selstr");
// process emails one by one
for ($i=1; $i <= $limit; $i++) {
$info = mysql_fetch_array($result);
// Process and send emails here.
// Do whatever you need to do.
}
// adjust $start and $end accordingly
$start = $start + $limit;
$end = $limit + $end;
// determine if rotation is necessary. If so, redirect script back to itself
// By re-directing back to the same script my goal is
// to prevent server time out
if ($batch % $rotate == '0') {
header("Location: ".$webaddress."email.php?start=".$start."&end=".$end."&batch=".$batch);
}
}
?>
Thanks for any input you can provide.
JeNNiDeS