Timeout a function in PHP

It depends on your implementation. 99% of the functions in PHP are blocking. Meaning processing will not continue until the current function has completed. However, if the function contains a loop you can add in your own code to interrupt the loop after a certain condition has been met.

Something like this:

foreach ($array as $value) {
  perform_task($value);
}

function perform_task($value) {
  $start_time = time();

  while(true) {
    if ((time() - $start_time) > 300) {
      return false; // timeout, function took longer than 300 seconds
    }
    // Other processing
  }
}

Another example where interrupting the processing IS NOT possible:

foreach ($array as $value) {
  perform_task($value);
}

function perform_task($value) {
    // preg_replace is a blocking function
    // There's no way to break out of it after a certain amount of time.
    return preg_replace('/pattern/', 'replace', $value);
}

What you want is to use the pcntl_alarm function, which will trigger a SIGALRM signal on timeout.

For example:

// 10 minutes
pcntl_alarm( 600 );
pcntl_signal(SIGALRM, function() { print( "Timed-out!\n" ); exit( 0 ); });

Please see here the PHP manual for more on this: http://php.net/manual/en/function.pcntl-alarm.php


PHP is single threaded... you have to use your OS's ability to fork another process.

The only way I know how to do this is with the exec command to fork off another full process. Put the stuff you want timed in a separate script, call exec on the script, then immediately sleep for 10 min. If at 10 min the process is still running kill it. (you should have it's PID by making the command run the new php code in the background, getting it via command line and returning it from the exec command).