


http browser actively disconnects and php actively disconnects
This article shares with you the http browser actively disconnecting and php actively disconnecting. Friends who are interested can take a look
Abstract: The cause of the incident is because of the usual encounters during development doubts. Once, after the browser client actively disconnected, it was found that the server-side php script was still executing, so I didn't know how to stop the script. Another time, there was a need to have the php script actively disconnect, and then the subsequent scripts continued to execute (a time-consuming task), so this blog was created.
1. The browser proactively disconnects
Under the commonly used LAMP combination, we believe that the browser accesses a php script, the script starts executing, the script outputs content, and ends running, apache In response to http, the browser receives the http response and displays the result.
Let’s consider special situations.
1. The browser sends an http request, and PHP performs a time-consuming task (20s) (assuming PHP's set_time_limit is set to 30s). During this period, the browser does not respond and the user clicks the browser X, the browser actively disconnects, does the php script continue to run?
Suppose the time-consuming task is: calculate fib(25), the browser test response takes 1.15s, each time the time-consuming task is executed, the file Log is written once, the time-consuming task is executed 10 times, and after the fifth execution At this time, the client actively disconnects and observes the situation.
The code is as follows:
<?phpfor ($i=0; $i < 10; $i++) { fib(25); setLog(date('H:i:s')); }function fib($n = 3){ if($n == 0){ return 1; } if($n == 1){ return 1; } return fib($n - 1) + fib($n -2); }function setLog( $massage, $path=''){ $log_path = empty($path)?'./log_'.date('Y-m-d').'.log':$path; $time = date('Y-m-d H:i:s'); $error_page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; file_put_contents($log_path, "LOG TIME:".$time.PHP_EOL, FILE_APPEND); file_put_contents($log_path, "LOG URL:".$error_page.PHP_EOL, FILE_APPEND); if(is_array($massage)){ $massage = json_encode($massage); } file_put_contents($log_path, "LOG MESSAGE:".$massage.PHP_EOL.PHP_EOL, FILE_APPEND); }?>
The browser disconnected when execution reached 5.44s.
The log shows: The script has been executed for 10 cycles.
This is different from what we thought before;
2. Optimize it. I saw it said on the Internet that PHP determines whether the client connection is disconnected when PHP outputs content to the client. The judgment is , then we modify the test code:
<phpfor ($i=0; $i < 10; $i++) { fib(25); setLog(date('H:i:s')); echo "hello"; } //这里省略了fib和setLog函数 ?>
Test again and find that the results are the same as the last test. The reason: when php outputs content to the client, there are three buffering stages, which are:
php buffer => web server buffer => browser buffer
Only when the buffer is full It will be output to the client. This is actually the principle of the back-end outputting content to the front-end every once in a while. Of course, you can also control the output to the client when the buffer is not full.
#3. Modify the test code again to make the content of the output client large enough: Instead of the previous demo, the script needs to be completely executed before the content is output to the client. At the same time, the client connection is closed at this time. When the server outputs content to the client again, it will check that the client connection has been disconnected. At this time, the script will stop running. This is the test result we want.
4. Modify the test code again. This time, instead of outputting a large amount of content at a time, the content of the buffer is deliberately manipulated, so that although the content is not enough to be output from the buffer to the client, it is output to the client in advance. client.
Test code: <?php$re = "";for($i=0; $i < 10000; $i++){ $re .= "aa";
}for ($i=0; $i < 10; $i++) {
fib(25);
setLog(date('H:i:s')); echo $re;
}//这里省略了fib和setLog函数?>
- But the premise is that PHP knows how the client disconnects. Only when PHP outputs content to the client (not the PHP buffer, not the web server buffer) will PHP know that the client connection is interrupted. , it will stop running;
- There are two ways for php to output content to the client. One is to fill the content into the buffer and automatically send it to the client; the other is to use ob_flush, the flush function to actively flush the buffer content to the client;
- php script operation is also subject to internal The script timer limit can be configured in php.ini or the host apache configuration file, or set through the set_time_limt function in the script;
- When the client actively disconnects, the php script When it does not stop running, it is also limited by the script timer;
- When the php script sets ignore_user_abort(true); then even if the client connection is disconnected, php outputs the content to the client Even if the client knows that the client connection is disconnected, it will not stop the script execution;
- #Internally, the connection status maintained by the system can be checked through the return value of the function connection_status, 0: normal; 1: aborted (disconnected); 2: timeout; The detection of changed status also requires the PHP script to output the content to the client to know, otherwise it will always be 0;
- In addition, there are There is a function that can also detect whether the client connection is disconnected (connection_aborted), 0 is normal, 1 is disconnected.
- A strange problem is that when the client connection has been disconnected and the php script outputs twice, the status bit becomes 1;
connection,当客户端收到响应头connection的值为close或者keep-alive,决定关闭当前tcp连接或者继续使用当前连接作下一次请求;
测试发现,当只指定conetent-length的时候也能达到php主动断开连接;
其实说是php主动断开连接,其实是php通知客户端主动断开的连接;
示例代码:
<?phpecho "hello world"; test();for ($i=0; $i < 10; $i++) { fib(25); setLog(date('H:i:s')); }function test(){ $size = ob_get_length(); header("content-length:" . $size); //header("connection:close"); ob_flush(); flush(); }//这里省略了fib和setLog函数?>
<完>
The above is the detailed content of http browser actively disconnects and php actively disconnects. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

HTTP status code 520 means that the server encountered an unknown error while processing the request and cannot provide more specific information. Used to indicate that an unknown error occurred when the server was processing the request, which may be caused by server configuration problems, network problems, or other unknown reasons. This is usually caused by server configuration issues, network issues, server overload, or coding errors. If you encounter a status code 520 error, it is best to contact the website administrator or technical support team for more information and assistance.

To remove FirefoxSnap in Ubuntu Linux, you can follow these steps: Open a terminal and log in to your Ubuntu system as administrator. Run the following command to uninstall FirefoxSnap: sudosnapremovefirefox You will be prompted for your administrator password. Enter your password and press Enter to confirm. Wait for command execution to complete. Once completed, FirefoxSnap will be completely removed. Note that this will remove versions of Firefox installed via the Snap package manager. If you installed another version of Firefox through other means (such as the APT package manager), you will not be affected. Go through the above steps

HTTP status code 403 means that the server rejected the client's request. The solution to http status code 403 is: 1. Check the authentication credentials. If the server requires authentication, ensure that the correct credentials are provided; 2. Check the IP address restrictions. If the server has restricted the IP address, ensure that the client's IP address is restricted. Whitelisted or not blacklisted; 3. Check the file permission settings. If the 403 status code is related to the permission settings of the file or directory, ensure that the client has sufficient permissions to access these files or directories, etc.

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

How to use NginxProxyManager to implement automatic jump from HTTP to HTTPS. With the development of the Internet, more and more websites are beginning to use the HTTPS protocol to encrypt data transmission to improve data security and user privacy protection. Since the HTTPS protocol requires the support of an SSL certificate, certain technical support is required when deploying the HTTPS protocol. Nginx is a powerful and commonly used HTTP server and reverse proxy server, and NginxProxy

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

Use the http.PostForm function to send a POST request with form data. In the http package of the Go language, you can use the http.PostForm function to send a POST request with form data. The prototype of the http.PostForm function is as follows: funcPostForm(urlstring,dataurl.Values)(resp*http.Response,errerror)where, u

Quick Application: Practical Development Case Analysis of PHP Asynchronous HTTP Download of Multiple Files With the development of the Internet, the file download function has become one of the basic needs of many websites and applications. For scenarios where multiple files need to be downloaded at the same time, the traditional synchronous download method is often inefficient and time-consuming. For this reason, using PHP to download multiple files asynchronously over HTTP has become an increasingly common solution. This article will analyze in detail how to use PHP asynchronous HTTP through an actual development case.
