What are the best practices for executing external programs in PHP to avoid script hanging and browser issues?
When executing external programs in PHP, it's important to use functions like `exec()` or `shell_exec()` instead of `system()` to avoid script hanging and potential browser issues. Additionally, setting a timeout for the execution can help prevent the script from running indefinitely. It's also recommended to sanitize user input to prevent any security vulnerabilities.
// Example code snippet for executing an external program with a timeout
$command = 'your_external_program_command_here';
$timeout = 60; // Set timeout to 60 seconds
$descriptorspec = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w") // stderr
);
$process = proc_open($command, $descriptorspec, $pipes);
if (is_resource($process)) {
stream_set_blocking($pipes[1], 0); // Set non-blocking for stdout
stream_set_blocking($pipes[2], 0); // Set non-blocking for stderr
$start_time = time();
$output = '';
$error_output = '';
while (!feof($pipes[1]) || !feof($pipes[2])) {
$read = array($pipes[1], $pipes[2]);
$write = NULL;
$except = NULL;
$timeout_remaining = $timeout - (time() - $start_time);
if ($timeout_remaining <= 0) {
break; // Timeout reached
}
if (stream_select($read, $write, $except, $timeout_remaining)) {
foreach ($read as $stream) {
if ($stream == $pipes[1]) {
$output .= fread($stream, 8192);
} elseif ($stream == $pipes[2]) {
$error_output .= fread($stream, 8192);
}
}
}
}
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
$return_value = proc_close($process);
echo "Output: " . $output;
echo "Error Output: " . $error_output;
}