PHP超时错误处理

问题描述:

I'm triyng to catch timeout error to output some clear text to the user (like "Sorry, timeout"). So why does this example:

function shutdown() { 
    $a=error_get_last(); 
    if($a==null)   
        echo "No errors"; 
    else 
         print_r($a); 

} 
register_shutdown_function('shutdown'); 
ini_set('max_execution_time',1 ); 
sleep(3); 

output no errors?? I'm confused about it. Here this example looks helpful. Thanks

我正在试图捕获超时错误以向用户输出一些明文(例如“抱歉,超时”) 。 为什么这个例子: p>

  function shutdown(){
 $ a = error_get_last();  
 if($ a == null)
 echo“No errors”;  
其他
 print_r($ a);  
 
} 
register_shutdown_function('shutdown');  
ini_set('max_execution_time',1);  
sleep(3);  
  code>  pre> 
 
 

输出没有错误 code> ?? 我很困惑。 div>

Try not using sleep(), seems to work if the reason for timeout is real work:

Example

function isPrime($num) {
    if($num == 1)
        return false;
    if($num == 2)
        return true;
    if($num % 2 == 0) {
        return false;
    }
    for($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2) {
        if($num % $i == 0)
            return false;
    }
    return true;
}
function shutdown() 
{ 
     $a=error_get_last(); 
     if($a==null)   
         echo "No errors"; 
     else 
          print_r($a); 
} 
register_shutdown_function('shutdown'); 
ini_set('max_execution_time',1 ); 
$ps = 0;
for ($i = 0; $i < 1000000; $i++) {
    if (isPrime($i)){
        $ps++;
    }
}
echo $ps;