title: Detecting a timeout for a block of code in PHP
body: <p>Is there a way you can abort a block of code if it's taking too long in PHP? Perhaps something like:</p>
  
  <pre><code>//Set the max time to 2 seconds
  $time = new TimeOut(2);
  $time-&gt;startTime();
  
  sleep(3)
  
  $time-&gt;endTime();
  if ($time-&gt;timeExpired()){
      echo 'This function took too long to execute and was aborted.';
  } 
  </code></pre>
  
  <p>It doesn't have to be exactly like above, but are there any native PHP functions or classes that do something like this?</p>
  
  <p><strong>Edit</strong>: Ben Lee's answer with <code>pcnt_fork</code> would be the perfect solution except that it's not available for Windows. Is there any other way to accomplish this with PHP that works for Windows and Linux, but doesn't require an external library? </p>
  
  <p><strong>Edit 2</strong>: XzKto's solution works in some cases, but not consistently and I can't seem to catch the exception, no matter what I try. The use case is detecting a timeout for a unit test. If the test times out, I want to terminate it and then move on to the next test.</p>