The method of long connection based on php and the matters needing attention

  • 2020-06-01 08:54:08
  • OfStack

php can be accessed by set_time_limit(0); To remove the php step timeout limit for long joins.

The example code is as follows:


<?php
echo " every 3 A second output 1 time <br />";
set_time_limit(0); // ensure php The program runs without timeout to exit 
while(1) {
   echo date("H:i:s")."<br />";
   ob_flush();
   flush(); // Refresh and output PHP The buffer data 
   sleep(3); // delay 3 seconds 
}
?>

Example code 2:


set_time_limit(0);
header("Connection:Keep-Alive");
header("Proxy-Connection:Keep-Alive");
for($i=0;$i<60;$i++) {
   print 'text'.$i.'<br>';
   ob_flush();
   flush();
   sleep(1);
   clearstatcache();
}

ob_flush(); flush (); To force the output data into a buffer so that the data can be returned to the browser in time before the footstep returns. In addition, the use of flush and ob_flush without flushing them has a particularly errant aspect, which makes it impossible to flush the output buffer.

1. The correct order of flush and ob_flush should be: ob_flush and flush first, as follows:

ob_flush();

flush();

If the operating system of the Web server is windows, it is not a problem to reverse the order or not use ob_flush(). However, the output buffer cannot be refreshed on the Linux system.

2. Before using ob_flush(), make sure the preceding content is large enough for 4069 characters.

1 the default of output_buffering of some Web servers is 4069 characters or larger, that is, the output content must reach 4069 characters before the server will flush refresh the output buffer. To ensure that flush is valid, it is better to have the following statement before the ob_flush() function:

print str_repeat(" ", 4096);

To ensure that the output_buffering value is reached.


for ($i=10; $i>0; $i--)
{
echo $i.'<br />';
ob_flush();
flush();
sleep(1);
}
ob_end_flush();


Related articles: