假设我正在运行我无法访问的外部脚本(请注意,这个问题并不是要问这样做会带来什么样的安全风险)我想让它在2秒内停止,无论如何。
当然,为了做到这一点,我不想放弃我的php.ini
。我都不想禁用安全模式来启用set_time_limit
。
是否有一种不会严重影响性能的解决方法?
我注意到性能,以避免回答,建议将代码作为字符串,憎恨 。通常,性能不很重要。
答案 0 :(得分:0)
我创建了一个简单的类,使用@Mark Baker建议的刻度来完成任务。如果有任何改进建议,我也placed in on 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) {
}
我需要知道如何绕过它。