title: PHP Long Polling Script Not Ending
body: <p>I have searched far and wide for a working answer and despite no shortage of questions on this issue, have not yet found one.</p>
  <p>I have a php script which checks the db for updates initiated by an ajax call with setTimeout. The page is like a game lobby where users can create, join or leave a game. When they do, the listening ajax function is aborted while the update occurs and then resumes straight after. This works perfectly with no delays or lag when I test it as a solo user but as soon as another user is on the page, the php script seems to hang up and not want to exit out of the loop, with nothing happening on the front end until it has timed out.</p>
  <p>I have added session_write_close, ob_flush and flush(), tried it with and without session_start, all to no avail. I'm sure websockets are better suited but they are currently not an option.</p>
  <p><strong>AJAX</strong></p>
  <pre><code>var hear,
      checking;
  function listen(){
      hear = $.ajax({
               url: &quot;check.php?last=0&quot;,
               success: function(data){
                   //do some stuff
                   checking = setTimeout({listen()}, 3000);
               }
      })
  }
               //NOW WHEN USER CLICKS JOIN FOR EXAMPLE-
  clearTimeout(checking);
  hear.abort();
                //Perform a different ajax call to update db, then resume listen()
  </code></pre>
  <p><strong>CHECK.php</strong></p>
  <pre><code>require_once(&quot;../abc/connection.php&quot;);  // connect to db
  
  //*******START OF VARIOUS TRIED SETTINGS
  session_start();
  $id = $_SESSION['id'];
  session_write_close();
  ignore_user_abort(1);      
  set_time_limit(40); 
  ini_set('zlib.output_compression', 0); 
  ini_set('implicit_flush', 1); 
  //*********END OF VARIOUS TRIED SETTINGS
  
  $last = isset($_GET['last']) ? mysqli_real_escape_string($_GET['last']) : 0 ;
  $true = 0;
  while($true &lt; 10){
      $true++;
      $str = &quot; &quot;;  //tried this line and below to help force script acknowledgement of ajax abortion
      echo $str;
      if(connection_status() != CONNECTION_NORMAL){
          echo str_repeat($str, 1024);      // In case of minimum output requirement 1KB
          ob_flush();
          flush();
          break;
      }
      $sql = mysqli_query($con, &quot;SELECT * FROM games WHERE id &gt; $last&quot;);
      if(mysqli_num_rows($sql) &gt; 0){
          echo &quot;Change detected&quot;;
          break;
      }else{
          mysqli_free_result($sql);
          sleep(3);
      }
  }
  </code></pre>
  <p>At this point I'm almost ready to revert back to just making the ajax call every 3 seconds. Very grateful for any help. Thanks</p>