2014-06-21 30 views
3

假設我正在運行我無法訪問的外部腳本(請注意,這個問題並不是要求這樣做有什麼安全風險),我希望它在2秒內停止,無論如何。如何在安全模式下降低PHP時間限制?

當然,我不想爲了做到這一點而使用我的php.ini。我也不想禁用安全模式來啓用set_time_limit

是否有一種解決方法不會大幅提升性能?

我注意到性能,以避免回答這個建議得到代碼串和eviluating每當事人之間。一般性能是不是重要。

+0

你可能想考慮一個'tick'函數:http://www.php.net/manual/en/function.register-tick-function.php –

+0

我試圖在此基礎上創建一些東西。是否有任何理由爲什麼剔回調不會被調用和/或滴答寄存器會默默地失敗? –

+0

你是否記得宣佈蜱? http://www.php.net/manual/en/control-structures.declare.php –

回答

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

我需要知道這是怎麼回事。