Home  >  Article  >  Backend Development  >  PHP中用set_time_limit(0)长连接的实现_PHP

PHP中用set_time_limit(0)长连接的实现_PHP

WBOY
WBOYOriginal
2016-06-01 12:20:43827browse

每次我们访问PHP脚本的时候,都是当所有的PHP脚本执行完成后,我们才得到返回结果。如果我们需要一个脚本持续的运行,那么我们就要通过php长连接的方式,来达到运行目的。

每个PHP脚本都限制了执行时间,所以我们需要通过 set_time_limit 来设置一个脚本的执行时间为无限长;然后使用 flush() 和 ob_flush() 来清除服务器缓冲区,随时输出脚本的返回值。

如下面这段脚本:

header("Content-Type: text/plain");
set_time_limit(0);

$infoString = "Hello World" . "\n";
while( isset($infoString) )
{
echo $infoString;
flush();
ob_flush();
sleep(5);
}
?>

当我们执行后,每隔5秒钟,我们会得到一行 Hello World ,如果不按停止按钮,浏览器会不停的一行一行继续加载。

通过这一方法,我们可以完成很多功能,例如机器人爬虫、即时留言板等程序。

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn