PHP set_time_limit of 0 long connection implementation analysis

  • 2020-03-31 20:24:24
  • OfStack

Each PHP script limits the execution time, so we need to set the execution time of a script to be infinite by 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.

Here's the script:
 
<?php 
header("Content-Type: text/plain"); 
set_time_limit(0); 

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

When we execute, we get a line of Hello World every 5 seconds, and if we don't press the stop button, the browser will continue loading line by line.

Through this method, we can accomplish many functions, such as robot crawler, instant message board and other programs.

Related articles: