Timeout a function in PHP
PHP does not offer a native set_timeout() function that you can slap onto an arbitrary callback to forcibly interrupt its execution mid-stream. If your script hits a hard limit, it either runs to completion or crashes entirely. However, achieving a 10-minute window for a batch job while abandoning individual slow steps requires architectural shifts rather than magic API calls.
The most robust solution involves wrapping your logic inside pcntl_signal() on Unix-like systems (Linux, macOS). This mechanism allows you to listen for a SIGALRM signal and set a hard stop after a specific duration. You can configure the alarm to trigger exactly 10 minutes from the start of the script.
Here is how to structure it:
<?php
$timeout = 600; // 10 minutes in seconds
// Set up the signal handler
pcntl_signal(SIGALRM, function () {
throw new RuntimeException("Maximum execution time of {$timeout} seconds exceeded.");
});
// Start the timer
pcntl_alarm($timeout);
try {
foreach ($arr as $key => $value) {
// Perform the SSH/SFTP operation
some_function($key, $value);
// Optional: Reset alarm if you want to allow 10 mins per item
// instead of total runtime. Uncomment below to do that.
// pcntl_alarm($timeout);
}
} catch (RuntimeException $e) {
echo "Job timed out gracefully at: " . date('Y-m-d H:i:s');
exit(1);
} finally {
// Cancel the alarm if we finish successfully or fail
pcntl_alarm(0);
}
?>
The Unix Limitation
This approach relies on pcntl, which is built into PHP but often disabled by default in production environments (especially on shared hosting). If pcntl is unavailable, you must rely on process management tools or system-level configuration. On standard web servers like Apache or Nginx, the timeout is usually enforced by php.ini settings (max_execution_time). If your script exceeds that limit, the web server kills the entire process.
If you are running this job via Cron, you can set a custom timeout using the -t flag on cron or system timers like at. For example:
# Run with a 600 second timeout
php -f your_script.php -t 600
This tells the shell to send SIGTERM after the specified seconds, giving PHP a chance to clean up before dying.
Handling Partial Failure
Your source material mentions that $arr has 15 elements and some_function() sometimes hangs for 5 minutes. If you use pcntl_alarm without resetting it inside the loop (as shown in the code above), the script will die globally after 10 minutes of total runtime. This means if item #8 takes 6 minutes, items #9 through #15 never run.
If your requirement is strictly "abort the current function call and move to the next," pcntl won't help you directly because it stops the whole script. To abort a single specific operation (like an SSH connection), you cannot simply kill() the PHP process; you must handle the timeout within the external tool itself.
SSH commands, for instance, accept a -o ConnectTimeout option. If your some_function wraps ssh or sftp, modify that call to include these flags:
ssh -o ConnectTimeout=300 user@host ...
This ensures that even if the PHP script waits indefinitely, the underlying network tool disconnects after 5 minutes.
Trade-offs and Pitfalls
A critical pitfall is resource leakage. If some_function opens an SFTP connection and then times out externally (via ConnectTimeout) or internally (via pcntl), you must ensure the resources are closed before moving to the next item. Using a try-catch-finally block around every external call is mandatory.
foreach ($arr as $key => $value) {
try {
some_function($key, $value);
} catch (Exception $e) {
// Log error and continue
error_log("Failed processing {$key}: " . $e->getMessage());
}
}
If the script runs in a container or a managed environment, ensure that max_execution_time in php.ini is not lower than your intended 10-minute window, or you will hit the server-level cutoff before your logic can handle it. For long-running tasks, consider using a message queue like RabbitMQ or Redis instead of polling with a loop; this decouples the processing speed from the script's runtime limits.
If you are building a SaaS product and need to manage these timeouts programmatically across many clients, look into orchestration platforms that handle execution lifecycles automatically. Resources like https://laravelcompany.com often discuss scalable queue patterns that can abstract away these raw PHP timeout mechanics.