Hello! Interested in the question - how can I properly stop the execution of a while loop with sleep inside. The fact is that I implement " long poll " to quickly update the information on the site (alerts, other information).
ESSENCE OF SCRIPT WORK
1. We send a GET request to the PHP page where the script is located.
2. The script starts the while loop .
3. In this cycle there are 2 conditions and sleep (1) at the end, which pauses the execution of the cycle.
- If if the cycle works for more than 30 seconds - stop the execution of the cycle, respectively, and the script.
- If a new information has appeared on the site, say βalertβ - output the result to the user and stop the cycle.
PROBLEM If the user closes the browser window, or reloads the page, a new request for this script will be executed, which will start the cycle again. But at the same time, the previous execution of the while loop will not stop until at least one condition inside it is triggered. If the user sends a lot of requests to the page - the server's memory starts to load heavily and as a result everything hangs until all while stops performing.
QUESTION How to stop the execution of the loop and the script as a whole when you re-execute it or reload the page by the client? So far, at the moment I have done the following. When executing the script, we generate a random number, which we write to the variable and also with the session. Further inside while I do a condition in which the given variable should equal session value. If false, stop the loop. If we run the script on a new one, the session value changes and, accordingly, all previous while executing stops. Can I use this option? And how safe is it?
UPDATE.PHP
// ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·ΠΈΡΡΠ΅ΠΌ ΡΠ΅ΡΡΠΈΡ ΠΏΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΠ΅Π»Ρ $session = Session::instance(); $rand = rand(); $session->set('user_update_key', $rand); $key = $rand; $limit = 20; $seconds = 0; set_time_limit($limit + 1); while (TRUE) { if (Session::instance()->get('user_update_key') == $key) { if (Π΅ΡΡΡ Π»ΠΈ ΠΎΠ±Π½ΠΎΠ²Π»Π΅Π½ΠΈΡ. Π΅ΡΠ»ΠΈ Π΅ΡΡΡ - Π²ΡΠ²ΠΎΠ΄ΠΈΠΌ) { echo 'ΠΈΠ½ΡΠΎΡΠΌΠ°ΡΠΈΡ ΠΎΠ±Π½ΠΎΠ²Π»Π΅Π½ΠΈΠΉ'; flush(); exit; } if ($seconds == $limit) { // Π·Π°Π²Π΅ΡΡΠ°Π΅ΠΌ Π²ΡΠΏΠΎΠ»Π½Π΅Π½ΠΈΠ΅ ΡΠΈΠΊΠ»Π° ΠΏΠΎ ΠΈΡΡΠ΅ΡΠ΅Π½ΠΈΡ Π²ΡΠ΅ΠΌΠ΅Π½ΠΈ. echo 'Close'; flush(); exit; } $seconds++; } else { unset($session, $rand, $key, $notice, $mysession, $last_notice, $limit, $notise_return, $seconds); flush(); exit; } session_write_close(); sleep(1); session_start();
}