如何在安全模式下减少PHP的时间限制


How to decrease PHP time limit in safe mode?

假设我正在运行外部脚本,我没有访问权限(请注意,这个问题不是问这样做的安全风险是什么),我希望它在2秒内停止,无论什么

当然,我不想为了这样做而承认我的php.ini。我也不想禁用安全模式来启用set_time_limit

是否有一个不影响性能的解决方案?

我注意性能以避免回答建议将代码作为字符串和评估每个部分。一般来说,性能不重要

我创建了一个简单的类,按照@Mark Baker的建议使用tick来完成任务。如果有任何改进建议,我也会在GitHub上放置。

declare(ticks=1);
//You don't need to use that function
function set_time_limit_safe($limit) {
  if(!is_numeric($limit))
    trigger_error("set_time_limit_safe() expects parameter 1 to be numeric value, ". gettype($limit)." given", E_USER_WARNING);
  TimeLimit::set($limit);
}
//I'm using class to have the possibility of private static that's shared between both
//set function and the callback
class TimeLimit {
    //Default value for limit
    private static $limit = 30;
    //When the limit is registered, this is set to current time for later comparisons
    private static $reg_time = -1;
    //Boolean to determine whether callback is already registered or not
    private static $registered = false;
    /**
* Sets the time limit and registers callback
* @param float $limit limiting time in seconds
* @return null
**/
    public static function set($limit) {
      //echo "Setting time limit!<br />";
      self::$limit = $limit;
      //Seconds as float
      self::$reg_time = microtime(true);
      //Only register once
      if(!self::$registered) {
        register_tick_function(array('TimeLimit', 'tick_cb'));
        //echo "Registering tick function!<br />";
        self::$registered = true;
      }
    }
    /**
* The callback
* You can disable the limit by unregistering this function
**/
    public static function tick_cb() {
      $time = microtime(true);
      //echo "Tick!!!<br />";
      if($time-self::$reg_time>=self::$limit) {
        trigger_error("User defined maximum execution time of ".self::$limit." seconds exceeded.", E_USER_ERROR);
        //In case error callback had let the error through
        exit;
      }
    }
}
//Testing code
set_time_limit_safe(1.5);
while(true) {
}

我需要知道如何绕过这个