我正在尝试编写一个函数,该函数可以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)。似乎当前的代码现在正在按预期工作,但非常感谢任何改进它的建议。
感谢您的反馈。
这只是
一个猜测;几年前,我写了一个非常不稳定的聊天脚本,它也使用输出缓冲(并在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();
}
?>
它对我有用,所以也许你也可以尝试一下。(虽然我不知道现代浏览器和服务器基础设施将如何对此起作用)。
我认为您可能正在寻找的是逐步运行和输出脚本,而不是异步函数。
请参阅有没有办法在脚本执行时使 PHP 逐步输出?