Home  >  Article  >  Backend Development  >  Methods and precautions for implementing long connections based on PHP_PHP Tutorial

Methods and precautions for implementing long connections based on PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:10:56812browse

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:

Copy the code The 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:

Copy code The code is as follows:

set_time_limit(0);

header("Connection:Keep-Alive");

header("Proxy-Connection:Keep-Alive");

for($i=0;$i<60;$i++) {

print 'text'.$i.'
';

ob_flush();

flush();

sleep(1);

clearstatcache();

}


Ob_flush(); flush(); is called here to force the output data to the buffer, so that the data can be returned to the browser in time before the step returns. In addition, there are some particularly easy mistakes in the use of flush and ob_flush, resulting in the inability to refresh the output buffer.

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.

Copy code The code is as follows:

for ($i=10; $i>0; $i--)

{

echo $i.'
';

ob_flush();

flush();

sleep(1);

}
ob_end_flush();

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327001.htmlTechArticlephp 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: Copy the code The code is as follows: ?php echo "Output every 3 seconds...
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