2014-09-23 41 views
0

我需要一些帮助我试图终止我的脚本,如果它达到60秒,如果它不能连接到服务器,但我总是抓住60秒限制执行时间。我想我的代码不管用。在60秒内终止脚本

<?php 
$time_limit = 60; 

set_time_limit ($time_limit); 

if(isset($_GET['comm'])){ 

    $command = $_GET['comm']; 

    $host = "xxx.xx.xxx.xx"; 
    $port = xxxx; 

    $start_time = time(); 
    $message = $command; 
    $socket = socket_create(AF_INET, SOCK_STREAM,0) or die("Could not create socket\n"); 

    while([email protected]_connect($socket, $host, $port)){ 

     if ((time() - $start_time) >= $time_limit) 
     { 
      socket_close($socket); 
      die("Connection timed out.\n"); 
     } 

     sleep(1); 
     continue; 

    } 

    socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n"); 
    $resultserv = socket_read ($socket, 1024) or die("Could not read server response\n"); 



    $curl = curl_init(); 

    curl_setopt_array($curl, array(
     CURLOPT_RETURNTRANSFER => 1, 
     CURLOPT_URL => 'http://tomysite/receive.php', 
     CURLOPT_POST => 1, 
     CURLOPT_POSTFIELDS => array(
      'recrespond' => $resultserv 

     ) 
    )); 

    $resp = curl_exec($curl); 

    curl_close($curl); 

    echo $resultserv; 

    socket_close($socket); 

} 

?> 

在此先感谢您。

+0

http://stackoverflow.com/questions/5164930/fatal-error-maximum-execution-time-of-30-seconds-exceeded你也显然不能设置超时在60时,这是PHP的时间限制以及它将需要在59. – mschuett 2014-09-23 02:18:11

回答

0

您需要添加ini_set('max_execution_time', 59);

+0

我相信他希望功能在时限到达之前超时。 – mschuett 2014-09-23 02:21:38

+0

但op没有提及它? – 2014-09-23 02:23:29

+0

是的,我知道但看着代码我相当肯定,这是他想要的。这个问题的措辞不是很好。 – mschuett 2014-09-23 02:24:48

0

设置$的时限= 55,因为60秒的PHP执行时间就要开始了你的脚本执行之前。如果你需要它运行60秒,我会使用相同的脚本,但使用ini_set()将执行时间增加到65秒。

+0

好的,我会尝试谢谢 – kelly123 2014-09-23 02:37:31

+0

我加了这个ini_set('max_execution_time',59);,然后$ time_limit = 55; set_time_limit($ time_limit);但脚本未终止 – kelly123 2014-09-23 03:08:34

+0

请勿使用set_time_limit。你说你的脚本只能运行55秒,当你这样做,它会覆盖ini_set(); – mschuett 2014-09-23 03:10:15