Stopping script mid execution on exit
<p>On a user action I am running a back end system script through an AJAX call which does not output until it is complete. The issue is that a user could easily waste resources by starting the script then leaving the page. The goal is to break out of a while loop on exit.</p>

<p>To start, I made it add a file to the cache when it starts and I check it on every iteration. That works correctly because if I change the file value through another AJAX call, it will exit.</p>

<p>So my question is, how can I break out of that loop when you leave the page?</p>

<p>My only guess is to do a JS onunload AJAX call to alter the cache file, but that's a poor and highly unreliable approach for obvious reasons. Thanks</p>

<p><strong>//Edit//</strong></p>

<p>So I have given connection_aborted a ignore_user_abort a shot. Here is a very watered down version of the code.</p>

<pre><code>ignore_user_abort(true);
set_time_limit(0);

$handle=opendir($dir);
if($handle)
{
    while(false!==($file=readdir($handle))&amp;&amp;!connection_aborted())
    {
       sleep(1);
       unlink($dir."/".$file);
    }
}
</code></pre>

<p>So even after I leave the page, the files are still being removed from the folder. My goal is to get out of that loop and stop all unlinking if you leave the page.</p>
