2014-09-23 113 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