DanMossa
DanMossa

Reputation: 1092

Perform a PHP loop every X seconds

I have the user type in how often they want a message sent as defined by the $time variable

This is the loop code I have right now

$time = $_POST["time"];

for ($x = 0; $x < $amount; $x++) {
    mail($completenum, $subject, $message, $headers);
    sleep($time);

}

The issue with this code is that the messages never get sent through, I believe it's because the sleep function halts the script. Any ideas?

Upvotes: 0

Views: 412

Answers (1)

Peter Barton
Peter Barton

Reputation: 587

PHP isn't really the correct language for this, you want to try javascript or similar.

PHP is designed to let you dynamically build a page when it is loaded. By putting a sleep in there, you're delaying the load time of the page, and the server and/or browser is eventually going to time out - pages aren't expected to take excessively long times to load, and that usually indicates an error. Different browsers are going to do different things, and you'd need to modify the timeout settings on everything if the delay is a long one.

A scripting language that keeps running in the browser is going to be able to kick something off periodically like you want, and even update the page - you want code that keeps executing AFTER the page is loaded.

Alternately, if you want PHP only, your PHP code could store the request in a database, and then you could have another 'processing' page that you hit periodically with a cron job or similar in the background, which sends out the emails as per the time delay. There are ways to achieve what you want with PHP only, depending on the actual end result you're after, but putting a sleep() into the loading of a page like this is unlikely to be a reliable solution.

Upvotes: 1

Related Questions