Home Backend Development PHP Tutorial An in-depth study of whether php will continue to execute after the browser exits

An in-depth study of whether php will continue to execute after the browser exits

Dec 29, 2017 pm 06:56 PM
firefox webkit Browser

Will php continue to execute after browsing is exited? The editor below will introduce to you whether php will continue to execute after the browser exits. I hope to be helpful.

Premise: What we are talking about here is the typical lnmp structure, nginx+php-fpm mode

If I have a php program that executes very slowly, even sleep() in the code, Then when the browser connects to the service, a php-fpm process will be started. However, if the browser is closed at this time, will the php-fpm process on the server continue to run at this time?

Today we are going to solve this problem.

The simplest experiment

The simplest way is to do an experiment. We write a program: use file_put_contents before and after sleep. Write to the log:

<?php
file_put_contents(&#39;/tmp/test.log&#39;, &#39;11111&#39; . PHP_EOL, FILE_APPEND | LOCK_EX);
sleep(3);
file_put_contents(&#39;/tmp/test.log&#39;, &#39;2222&#39; . PHP_EOL, FILE_APPEND | LOCK_EX);
Copy after login

The result of the actual operation is that if we close the client browser while the server is sleeping, 2222 will be written to the log.

So this means that after the browser is closed, the server-side php will still continue to run?

ignore_user_abort

Lao Wang and diogin reminded that this may be related to php's ignore_user_abort Function related.

So I changed the code slightly to look like this:

<?php
ignore_user_abort(false);
file_put_contents(&#39;/tmp/test.log&#39;, &#39;11111&#39; . PHP_EOL, FILE_APPEND | LOCK_EX);
sleep(3);
file_put_contents(&#39;/tmp/test.log&#39;, &#39;2222&#39; . PHP_EOL, FILE_APPEND | LOCK_EX);
Copy after login
Copy after login

I found that there is no software use. No matter what value ignore_user_abort is set to, it will continue to execute.

But here is a question: What is user_abort?

The document makes it very clear about abort in cli mode. When the php script is executed and the user terminates the script, abort will be triggered. The script then determines whether to continue execution based on ignore_user_abort.

But the official document does not clearly describe abort in cgi mode. It seems that even if the client disconnects, PHP in cgi mode will not receive abort.

Does ignore_user_abort have no effect in cgi mode?

Is it a heartbeat problem?

The first thing that comes to mind is a heartbeat problem? When we disconnect the browser client, it is equivalent to disconnecting the connection without closing the client. The server needs to wait for the TCP keepalive to arrive before detecting it.

Okay, you need to eliminate the keepalive problem in the browser settings first.

Abandon the browser and simply write a client program: After the program connects to the http service, it sends a header and sleeps for 1 second before actively closing the connection. However, this program does not have the keepalive header of http.

The program is as follows:

package main

import "net"
import "fmt"
import "time"

func main() {
  conn, _ := net.Dial("tcp", "192.168.33.10:10011")
  fmt.Fprintf(conn, "GET /index.php HTTP/1.0\r\n\r\n")
  time.Sleep(1 * time.Second)
  conn.Close()
  return
}
Copy after login

Server program:

<?php
ignore_user_abort(false);
file_put_contents(&#39;/tmp/test.log&#39;, &#39;11111&#39; . PHP_EOL, FILE_APPEND | LOCK_EX);
sleep(3);
file_put_contents(&#39;/tmp/test.log&#39;, &#39;2222&#39; . PHP_EOL, FILE_APPEND | LOCK_EX);
Copy after login
Copy after login

It is found that it is still the same. PHP will continue to execute the entire process regardless of whether ignore_user_abort is set or not. script. It seems that ignore_user_abort still does not take effect.

How to trigger ignore_user_abort

How to trigger ignore_user_abort? How does the server know that this socket cannot be used? Lao Wang and Diogin asked whether the server needs to actively interact with the socket to determine whether the socket can be used?

In addition, we also found that PHP provides two methods, connection_status and connection_aborted, both of which can detect the current connection status. So our logging line of code can be changed to:

file_put_contents(&#39;/tmp/test.log&#39;, &#39;1 connection status: &#39; 
. connection_status() 
. "abort:" 
. connection_aborted() 
. PHP_EOL, FILE_APPEND | LOCK_EX);
Copy after login

According to the manual connection processing display, we can print out the current connection status.

The following still lacks a program that interacts with the socket. We use echo, and remember to bring flush later to eliminate the influence of flush.

The program will be changed to

<?php
ignore_user_abort(true);
file_put_contents(&#39;/tmp/test.log&#39;, &#39;1 connection status: &#39; . connection_status() . "abort:" . connection_aborted() . PHP_EOL, FILE_APPEND | LOCK_EX);
sleep(3);
for($i = 0; $i < 10; $i++) {
    echo "22222";
    flush();
    sleep(1);
    file_put_contents(&#39;/tmp/test.log&#39;, &#39;2 connection status: &#39; . connection_status() . "abort:" . connection_aborted(). PHP_EOL, FILE_APPEND | LOCK_EX);
}
Copy after login

Very good, execute the client we wrote earlier. Observation log:


1 connection status: 0abort:0
2 connection status: 0abort:0
2 connection status: 1abort:1
2 connection status: 1abort:1
2 connection status: 1abort:1
2 connection status: 1abort:1
2 connection status: 1abort:1
2 connection status: 1abort:1
2 connection status: 1abort:1
2 connection status: 1abort:1
2 connection status: 1abort:1
Copy after login

Finally made abort. The log also shows that the abort status for the next few times is 1.

But there is something strange here, why is the status of the first 2 connection status still 0 (NORMAL).

RST

We use wireshark to capture packets to see the entire interaction process between the client and the server

This The whole process only sends 14 packets. Let's see that when the server sends 22222 for the first time, the client returns RST. There will be no subsequent package requests.

So I understood that the approximate interaction process between the client and the server is:

When the server sends 2222 for the first time in the loop, the client has disconnected, What is returned is an RST, but the sending process is regarded as a successful request. Until the second time the server wants to perform a write operation on this socket again, this socket will not perform network transmission, and directly returns that the connection status is abort. So the above situation occurred. The first time 222 was status was 0, and the abort appeared only the second time.

strace for verification

We can also use strace php -S XXX for verification

The strace log of the entire process is as follows:

close(5)                = 0
lstat("/tmp/test.log", {st_mode=S_IFREG|0644, st_size=49873651, ...}) = 0
open("/tmp/test.log", O_WRONLY|O_CREAT|O_APPEND, 0666) = 5
fstat(5, {st_mode=S_IFREG|0644, st_size=49873651, ...}) = 0
lseek(5, 0, SEEK_CUR)          = 0
lseek(5, 0, SEEK_CUR)          = 0
flock(5, LOCK_EX)            = 0
write(5, "1 connection status: 0abort:0\n", 30) = 30
close(5)                = 0
sendto(4, "HTTP/1.0 200 OK\r\nConnection: clo"..., 89, 0, NULL, 0) = 89
sendto(4, "111111111", 9, 0, NULL, 0)  = 9
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigaction(SIGCHLD, NULL, {SIG_DFL, [], 0}, 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
nanosleep({3, 0}, 0x7fff60a40290)    = 0
sendto(4, "22222", 5, 0, NULL, 0)    = 5
open("/tmp/test.log", O_WRONLY|O_CREAT|O_APPEND, 0666) = 5
fstat(5, {st_mode=S_IFREG|0644, st_size=49873681, ...}) = 0
lseek(5, 0, SEEK_CUR)          = 0
lseek(5, 0, SEEK_CUR)          = 0
flock(5, LOCK_EX)            = 0
write(5, "2 connection status: 0abort:0\n", 30) = 30
close(5)                = 0
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigaction(SIGCHLD, NULL, {SIG_DFL, [], 0}, 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
nanosleep({1, 0}, 0x7fff60a40290)    = 0
sendto(4, "22222", 5, 0, NULL, 0)    = -1 EPIPE (Broken pipe)
--- SIGPIPE {si_signo=SIGPIPE, si_code=SI_USER, si_pid=2819, si_uid=0} ---
open("/tmp/test.log", O_WRONLY|O_CREAT|O_APPEND, 0666) = 5
fstat(5, {st_mode=S_IFREG|0644, st_size=49873711, ...}) = 0
lseek(5, 0, SEEK_CUR)          = 0
lseek(5, 0, SEEK_CUR)          = 0
flock(5, LOCK_EX)            = 0
write(5, "2 connection status: 1abort:1\n", 30) = 30
close(5)                = 0
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigaction(SIGCHLD, NULL, {SIG_DFL, [], 0}, 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
nanosleep({1, 0}, 0x7fff60a40290)    = 0
open("/tmp/test.log", O_WRONLY|O_CREAT|O_APPEND, 0666) = 5
fstat(5, {st_mode=S_IFREG|0644, st_size=49873741, ...}) = 0
lseek(5, 0, SEEK_CUR)          = 0
lseek(5, 0, SEEK_CUR)          = 0
flock(5, LOCK_EX)            = 0
write(5, "2 connection status: 1abort:1\n", 30) = 30
close(5) 
。。。我们照中看status从0到1转变的地方。
...
sendto(4, "22222", 5, 0, NULL, 0)    = 5
...
write(5, "2 connection status: 0abort:0\n", 30) = 30
close(5)                = 0
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigaction(SIGCHLD, NULL, {SIG_DFL, [], 0}, 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
nanosleep({1, 0}, 0x7fff60a40290)    = 0
sendto(4, "22222", 5, 0, NULL, 0)    = -1 EPIPE (Broken pipe)
--- SIGPIPE {si_signo=SIGPIPE, si_code=SI_USER, si_pid=2819, si_uid=0} ---
open("/tmp/test.log", O_WRONLY|O_CREAT|O_APPEND, 0666) = 5
fstat(5, {st_mode=S_IFREG|0644, st_size=49873711, ...}) = 0
lseek(5, 0, SEEK_CUR)          = 0
lseek(5, 0, SEEK_CUR)          = 0
flock(5, LOCK_EX)            = 0
write(5, "2 connection status: 1abort:1\n", 30) = 30
close(5)
Copy after login

第二次往socket中发送2222的时候显示了Broken pipe。这就是程序告诉我们,这个socket已经不能使用了,顺便php中的connection_status就会被设置为1了。后续的写操作也都不会再执行了。

总结

正常情况下,如果客户端client异常推出了,服务端的程序还是会继续执行,直到与IO进行了两次交互操作。服务端发现客户端已经断开连接,这个 时候会触发一个user_abort,如果这个没有设置ignore_user_abort,那么这个php-fpm的程序才会被中断。

至此,问题结了。

相关推荐:

PHP 底层的运行机制与原理

php cgi与fpm关系

PHP简单实现socks5代理服务器

The above is the detailed content of An in-depth study of whether php will continue to execute after the browser exits. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? Apr 19, 2025 pm 02:21 PM

The browser's unresponsive method after the WebSocket server returns 401. When using Netty to develop a WebSocket server, you often encounter the need to verify the token. �...

Why can't JavaScript directly obtain hardware information on the user's computer? Why can't JavaScript directly obtain hardware information on the user's computer? Apr 19, 2025 pm 08:15 PM

Discussion on the reasons why JavaScript cannot obtain user computer hardware information In daily programming, many developers will be curious about why JavaScript cannot be directly obtained...

Can JWT implement dynamic permission changes? What is the difference from the Session mechanism? Can JWT implement dynamic permission changes? What is the difference from the Session mechanism? Apr 19, 2025 pm 06:12 PM

Confusion and answers about JWT and Session Many beginners are often confused about their nature and applicable scenarios when learning JWT and Session. This article will revolve around J...

What to do if the USDT transfer address is incorrect? Guide for beginners What to do if the USDT transfer address is incorrect? Guide for beginners Apr 21, 2025 pm 12:12 PM

After the USDT transfer address is incorrect, first confirm that the transfer has occurred, and then take measures according to the error type. 1. Confirm the transfer: view the transaction history, obtain and query the transaction hash value on the blockchain browser. 2. Take measures: If the address does not exist, wait for the funds to be returned or contact customer service; if it is an invalid address, contact customer service and seek professional help; if it is transferred to someone else, try to contact the payee or seek legal help.

How to correctly generate and display the WeChat applet with parameters QR codes in Java? How to correctly generate and display the WeChat applet with parameters QR codes in Java? Apr 19, 2025 pm 04:48 PM

Generating a WeChat applet QR code with parameters in Java and displaying it on an HTML page is a common requirement. This article will discuss in detail how to use J...

Can two exchanges convert coins to each other? Can two exchanges convert coins to each other? Can two exchanges convert coins to each other? Can two exchanges convert coins to each other? Apr 22, 2025 am 08:57 AM

Can. The two exchanges can transfer coins to each other as long as they support the same currency and network. The steps include: 1. Obtain the collection address, 2. Initiate a withdrawal request, 3. Wait for confirmation. Notes: 1. Select the correct transfer network, 2. Check the address carefully, 3. Understand the handling fee, 4. Pay attention to the account time, 5. Confirm that the exchange supports this currency, 6. Pay attention to the minimum withdrawal amount.

How to register an account on Ouyi Exchange Ouyi Exchange Registration Tutorial How to register an account on Ouyi Exchange Ouyi Exchange Registration Tutorial Apr 24, 2025 pm 02:06 PM

The steps to register an Ouyi account are as follows: 1. Prepare a valid email or mobile phone number and stabilize the network. 2. Visit Ouyi’s official website. 3. Enter the registration page. 4. Select email or mobile phone number to register and fill in the information. 5. Obtain and fill in the verification code. 6. Agree to the user agreement. 7. Complete registration and log in, carry out KYC and set up security measures.

Web3 trading platform ranking_Web3 global exchanges top ten summary Web3 trading platform ranking_Web3 global exchanges top ten summary Apr 21, 2025 am 10:45 AM

Binance is the overlord of the global digital asset trading ecosystem, and its characteristics include: 1. The average daily trading volume exceeds $150 billion, supports 500 trading pairs, covering 98% of mainstream currencies; 2. The innovation matrix covers the derivatives market, Web3 layout and education system; 3. The technical advantages are millisecond matching engines, with peak processing volumes of 1.4 million transactions per second; 4. Compliance progress holds 15-country licenses and establishes compliant entities in Europe and the United States.

See all articles