在60秒内终止脚本


terminate script within 60 seconds

我需要一些帮助,如果脚本无法连接到服务器,如果脚本达到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(!@socket_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);
}
?>

提前谢谢。

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

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