如果已经过了n个时间量,如何在php脚本上设置计时器,输出错误消息和杀死脚本?

This might be a simple question, but I'm fairly new to PHP and am having a hard time figuring this out. So, a little background - my script gets called from a web based app that lets users run simple commands on remote machines. Example, the user can click a button to cat a log file on a remote machine, and it will display the output to the user. Now, if there's a connectivity issue and ssh isn't configured properly on the target server it can just hang forever and the ssh won't time out. In order to display a better error to the user than the php or fastCGI timeouts, I want to kill the script and display the command the user was running before the timeouts occur. For simplicity, lets say my timeouts for IIS/FastCGI/PHP are all set to 5 minutes. I want to set a timer when the script gets kicked off, and if 4 minutes and 45 seconds have passed, I want to kill the script and display an error message to the user that displays the command they were trying to run so they can troubleshoot manually.

In stub/psuedo code for a simple example:

function StartTimer(){

//start timer 

}

function RunComand($cmd, $timer, $timeMax){

 //runs user command through ssh library and streams back output.
 $output = sshLib($cmd);

 //this is where i want to do my check on the timer. If run through ssh lib takes too long
 //kill the script and return $cmd to display it to user.

 if ($timer > $timeMax){
     //kill script, output $cmd
 }
 return $output;

}

$cmd = $_GET['cmd']  //get users command
$timer = startTimer();
$timeMax = 285; //285 seconds is 4 min 45 seconds

$results = RunCommand($cmd, $timer, $timeMax);

You could use Bunsen, "an advanced, object-oriented program execution library for PHP".

Here's an example:

<?php

require 'Bunsen.class.php';

// You should DEFINITELY sanatize the contents of `$_GET['cmd']` !!!
$cmd = $_GET['cmd'];
$timeMax = 285;

$bunsen = new Bunsen;
$bunsen->setTimeout($timeMax);

$exitcode = $bunsen->exec($cmd);

if ($exitcode === -1) {
    trigger_error('Maximum time limit exceeded!', E_USER_ERROR);
}

You should be VERY careful about running arbitrary commands that anyone could just put in the query string of their URL. It would be better if you had something like this:

switch($_GET['cmd']) {
case 1:
    $cmd = 'first command';
    break;
case 2:
    $cmd = 'second command';
    break;
case 3:
    $cmd = 'third command';
    break;
default:
    trigger_error('Not allowed!', E_USER_ERROR);
}

That way they can only run known safe commands from a whitelist.