title: How to restructure a long running php process to not time out
body: <p>I have a simple javascript function like so:</p>
  
  <pre><code>$(document).ready(function(){
      var request = $.ajax({
          url: "read_images.php",
          type: "GET",
          dataType: "html"
      });
      request.done(function(msg) {
          $("#mybox").html(msg);
          document.getElementById('message').innerHTML = '';
      });
      request.fail(function(jqXHR, textStatus) {
          alert( "Request failed: " + textStatus );
      });
  });
  </code></pre>
  
  <p>The php script it is calling loops on the contents of a folder, runs some checks, and returns a response. The script is as follows:</p>
  
  <pre><code>//Get all Images from server, store in variable
  $server_images = scandir('../images/original');
  
  //Remove first 3 elements, which are not correct
  array_shift($server_images);
  array_shift($server_images);
  array_shift($server_images);
  
  $j = 0;
  for($i=0;$i&lt;count($server_images) &amp;&amp; $i&lt;3000;$i++) {
       $server_image = $server_images[$i];
  
      //Make sure that the server image does not have a php extension
      if(!preg_match('/.php/',$server_image)) {
  
      //Select products_id and name from table where the image name is equal to server image name
      $query = "SELECT `name`
              FROM `images`
              WHERE `name` = '$server_image'";
      $mro_images = $db-&gt;query($query);
      $mro_images_row = $mro_images-&gt;fetch();
      $mro_image = $mro_images_row['name'];
  
      //If no results are found
      if(empty($mro_image)) {
          $images[$j] = $server_image;
          $j++;
      }
  }
  }
  </code></pre>
  
  <p>It works if the loop is restricted to 2000 iterations but if I try to do e.g. 3000 iterations the result is:</p>
  
  <pre><code>HTTP/1.1 500 Internal Server Error 31234ms
  </code></pre>
  
  <p>I've tried increasing the php execution limit, but this didn't have any effect as, after contacting my host:</p>
  
  <blockquote>
    <p>Unfortunately in our environment we don't have any way to increase the loadbalancer timeout beyond 30 seconds</p>
  </blockquote>
  
  <p>Therefore: How can I restructure this code to avoid hitting the execution time limit?</p>