如何在php脚本上设置计时器,输出错误消息,并在经过n段时间后终止脚本



这可能是一个简单的问题,但我对PHP相当陌生,很难弄清楚。所以,有一点背景——我的脚本是从一个基于web的应用程序调用的,该应用程序允许用户在远程机器上运行简单的命令。例如,用户可以单击一个按钮在远程机器上创建日志文件,它将向用户显示输出。现在,如果存在连接问题,并且ssh没有在目标服务器上正确配置,它可能会永远挂起,ssh不会超时。为了向用户显示比php或fastCGI超时更好的错误,我想终止脚本并显示用户在超时发生之前运行的命令。为了简单起见,假设我对IIS/FastCGI/PHP的超时都设置为5分钟。我想在脚本启动时设置一个计时器,如果已经过了4分45秒,我想终止脚本,并向用户显示一条错误消息,显示他们试图运行的命令,以便他们可以手动进行故障排除。

在stub/psuedo代码中有一个简单的例子:

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);

您可以使用Bunsen,"一个用于PHP的高级、面向对象的程序执行库"。

这里有一个例子:

<?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);
}

您应该非常小心地运行任意命令,任何人都可以将其放入URL的查询字符串中。如果你有这样的东西会更好:

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);
}

这样,他们只能从白名单中运行已知的安全命令。

最新更新