PHP can cancel the PHP script timeout limit through set_time_limit(0); to achieve the effect of long connection.
The example code is as follows:
echo "Output every 3 seconds
";
set_time_limit(0); //Ensure that the php program does not timeout and exit
while(1) {
echo date("H:i:s")."
";
ob_flush();
flush(); //Refresh and output PHP buffer data
sleep(3); //Delay 3 seconds
}
?>
Sample code 2:
header("Connection:Keep-Alive");
header("Proxy-Connection:Keep-Alive");
for($i=0;$i<60;$i++) {
print 'text'.$i.'
';
ob_flush();
flush();
sleep(1);
clearstatcache();
}
1. The correct order of flush and ob_flush, the correct order is, ob_flush first and then flush, as follows:
ob_flush();
flush();
If the operating system of the web server is a windows system, there will be no problem if the order is reversed or ob_flush() is not used. But on Linux systems, the output buffer cannot be flushed.
2. Before using ob_flush(), make sure the previous content size is enough to 4069 characters.
The output_buffering of some web servers defaults to 4069 characters or larger, that is, the output content must reach 4069 characters before the server flushes the output buffer. In order to ensure that the flush is effective, it is best to have the following statement before the ob_flush() function:
print str_repeat(" ", 4096);
to ensure the output_buffering value is reached.
{
echo $i.'
';
ob_flush();
flush();
sleep(1);
}
ob_end_flush();