


An in-depth study of whether php will continue to execute after the browser exits
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('/tmp/test.log', '11111' . PHP_EOL, FILE_APPEND | LOCK_EX); sleep(3); file_put_contents('/tmp/test.log', '2222' . PHP_EOL, FILE_APPEND | LOCK_EX);
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('/tmp/test.log', '11111' . PHP_EOL, FILE_APPEND | LOCK_EX); sleep(3); file_put_contents('/tmp/test.log', '2222' . PHP_EOL, FILE_APPEND | LOCK_EX);
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 }
Server program:
<?php ignore_user_abort(false); file_put_contents('/tmp/test.log', '11111' . PHP_EOL, FILE_APPEND | LOCK_EX); sleep(3); file_put_contents('/tmp/test.log', '2222' . PHP_EOL, FILE_APPEND | LOCK_EX);
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('/tmp/test.log', '1 connection status: ' . connection_status() . "abort:" . connection_aborted() . PHP_EOL, FILE_APPEND | LOCK_EX);
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('/tmp/test.log', '1 connection status: ' . 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('/tmp/test.log', '2 connection status: ' . connection_status() . "abort:" . connection_aborted(). PHP_EOL, FILE_APPEND | LOCK_EX); }
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
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)
第二次往socket中发送2222的时候显示了Broken pipe。这就是程序告诉我们,这个socket已经不能使用了,顺便php中的connection_status就会被设置为1了。后续的写操作也都不会再执行了。
总结
正常情况下,如果客户端client异常推出了,服务端的程序还是会继续执行,直到与IO进行了两次交互操作。服务端发现客户端已经断开连接,这个 时候会触发一个user_abort,如果这个没有设置ignore_user_abort,那么这个php-fpm的程序才会被中断。
至此,问题结了。
相关推荐:
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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment