逐步输出exec()ping结果

时间:2012-05-29 22:27:50

标签: php buffer exec ping flush

我正在尝试编写一个ping几百个地址并返回其值(毫秒)的函数。到目前为止,我已经实现了最初的想法,即ping和获得结果,但是当对数百个地址使用相同的代码时出现问题,PHP页面停止,直到它超时或到达最后一个ping命令。

如果我能得到一些建议逐步输出结果,我会很高兴,这是我目前的代码:

<?php

// "for" loop added according to suggestion for browser compatibility (IE, FF, CHR, OPR, SFR)
for($i = 0; $i < 5000; $i++)
{
    echo ' ';
}

function GetPing($ip = NULL) {
    // Returns the client ping if no address has been passed to the function
    if(empty($ip)) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    // Check which OS is being run by the client
    if(getenv('OS') == 'Windows_NT') {
        //echo '<b>Detected local system:</b> Windows NT/2000/XP/2003/2008/Vista/7<p>';
        $exec = exec("ping -n 1 -l 32 -i 128 " . $ip);
        return end(explode(' ', $exec));
    }
    else {
        //echo '<b>Detected local system:</b> Linux/Unix<p>';
        $exec = exec("ping -c 1 -s 32 -t 128 " . $ip);
        $array = explode('/', end(explode('=', $exec )));
        return ceil($array[1]) . 'ms';
    }
    // ob_flush and flush added according to suggestion for buffer output
    ob_flush();
    flush();
}

// Added to test 20 sequential outputs
for($count = 0; $count < 20; $count++)
    echo GetPing('8.8.8.8') . '<div>';

?>

经过一些反馈,我已经为我的脚本添加了 for 循环以及ob_flush()和flush(),并且我还在 php.ini中将output_buffering设置为0 。它似乎适用于我目前测试的大多数浏览器(IE8,Firefox 12,Chrome 19,Opera 11,Safari 5)。目前的代码似乎正在按预期工作,但任何改进它的建议都非常受欢迎。

感谢您的反馈。

2 个答案:

答案 0 :(得分:1)

这只是猜测;我多年前写过一个非常摇摆不定的聊天脚本,它也使用输出缓冲(并在while(true)循环中获取新消息)..

在执行此操作时,我遇到了相同的问题,有时脚本停滞(空白屏幕),有时需要一段时间才会出现字符,此外这也是浏览器特定的。

以下是我添加到脚本中的相关代码片段,以使其与IE6和FF2一起使用(正如我多年前所说的那样......)

<?php
    // End output buffering
    ob_end_flush(); 

    // IE and Safari Workaround
    // They will only display the webpage if it's completely loaded or
    // at least 5000 bytes have been "printed".
    for($i=0;$i<5000;$i++)
    {
        echo ' ';
    }

    while( ... )
    {
        echo 'Message';
        ob_flush();
        flush();
    }
?>

它对我有用,所以也许你也可以尝试一下。 (尽管我不知道现代浏览器和服务器基础架构将如何表现如此)。

答案 1 :(得分:0)

我认为您可能正在寻找的是逐步运行并输出脚本,而不是异步函数。

请参阅Is there a way to make PHP progressively output as the script executes?

相关问题