Home > Backend Development > PHP Tutorial > Implementation of long connection in PHP

Implementation of long connection in PHP

WBOY
Release: 2016-08-08 09:31:05
Original
1240 people have browsed it

Recently, I encountered a PHP program prompting a timeout when executing a large amount of data, so I used the set_time_limit() function to set the maximum running time of the PHP page.
Set the number of seconds the script is allowed to run. If this is the default, the script returns a fatal error. The default limit is 30 seconds, or you can set the maximum execution time of the PHP page by defining max_execution_time in php.ini.
When called, the set_time_limit() function restarts the timeout counter from zero. In other words, if the timeout is 30 seconds by default, 25 seconds to the script's execution parameter or set_time_limit, if the timeout is set to (20), the script will run for 45 seconds before timing out.
set_time_limit(900) This function specifies the maximum execution time of the current php script. Although the set value is 900 seconds, the actual maximum execution time = the max_execution_time value in php.ini - the execution time of the current script + the set value.
If max_execution_time=30 in php.ini and the current script has been executed for 10 seconds, then:
Maximum execution time=30-10+900=920 seconds.
After such modification, the PHP script successfully updated 200,000 records.
Every time we access a PHP script, we only get the return result after all PHP scripts have been executed. If we need a script to run continuously, then we must use PHP long connection to achieve the purpose of operation.

Every PHP script has a limited execution time, so we need to set the execution time of a script to unlimited through set_time_limit; then use flush() and ob_flush() to clear the server buffer and output the return value of the script at any time.

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

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

When we execute, every 5 seconds, we will get a line of Hello World. If you do not press the stop button, the browser will continue to load line by line.
Through this method, we can complete many functions, such as robot crawlers, instant message boards and other programs.

The above introduces the implementation of long connections in PHP, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template