Home >Backend Development >PHP Tutorial >PHP actively disconnects from the browser_PHP Tutorial
PHP actively disconnects from the browser
I once compiled an article "In-depth analysis of set_time_limit(), connection_status() and ignore_user_abort() in PHP connection processing", which explains the processing of server PHP scripts when the browser client is disconnected.
This article will explain how the server PHP script actively disconnects from the browser. The main method is to use Content-Length and Connection in the http protocol header
The role of Content-Length: After the browser receives the message entity with the specified Content-Length size, it will disconnect from the server.
The role of Connection: After the browser receives the Close or Keep-Alive of the Connection, it decides whether to close the connection or continue to use the current connection for the next request.
/**
* Automatically disconnect from the browser
* jiaofuyou
*/
echo '1234567890'; //Content output to the browser
{//Disconnect code
$size=ob_get_length();
Header("Content-Length: $size"); //Tell the browser the data length. After the browser receives this length of data, it will no longer receive data
Header("Connection: Close"); //Tell the browser to close the current connection, which is a short connection
ob_flush();
flush();
}
error_log(date("[Y-m-d H:i:s]")." > "."start" ."n", 3 , "/usr/local/apache2219/logs/php_log");
//Perform long-term operations after disconnection
sleep(5);
echo 'test213';//The browser cannot receive it
error_log(date("[Y-m-d H:i:s]")." > "."end" ."n", 3 , "/usr/local/apache2219/logs/php_log");
//You can check whether the error log is executed after a delay of 5 seconds.
?>
Description:
1. Using Content-length alone does not actually disconnect the connection. It just stops the browser from receiving information. Connection: Close actually tells the browser to close the connection.
2. Specifying Content-Length has no meaning for file_get_contents; if you want to use it, please use curl.
If you want PHP to continuously output content to the browser:
echo "1234567890"
ob_flush();
flush();
This will not be output to the browser immediately, you can do this
echo "1234567890
"
//When there is a line break, it will be output to the browser immediately
ob_flush();
flush();
Or:
echo "1234567890"
print str_pad("",10000); //Output enough content
ob_flush();
flush();