PHP 在 Nginx 下主动断开连接 Connection Close 与 ignore_user_abort 后台运行
PHP 在 Nginx 下主动断开连接 Connection Close 与 ignore_user_abort 后台运行
这两天弄个PHP调用 SVN 同步 update 多台服务器更新的程序,为了避免 commit 的时候不会被阻塞卡半天得想个办法只请求触发,而不需要等待程序 update 完成返回结果这样耗时太长,所以研究过了下如何让PHP主动断开连接的方法。搞了一下午,发现很多问题,还好最终还是弄出来了,主要是 Nginx 太坑。。
废话不多说,下面上代码:
<code class="hljs" java="">/** * 主动断开与客户端浏览器的连接 * 如果是 Nginx 服务器需要输出大于等于 fastcgi_buffer_size 缓存的数据才能即时输出 header 断开连接, 若还是不行可尝试关闭 gzip * 如: fastcgi_buffer_size 64k; 即: 需要 64*1024 字符(可多不可少), * 可使用 str_repeat(' ', 65536); 另外 str_repeat(' ', 6554); 这种方式其实生成速度更慢 * @param null|string $str 当前输出的内容, 若无需输出则设置为空 */ public function connectionClose($str = null) { $str = ob_get_contents() . $str; // 若实际输出内容长度小于该值将可能导致主动断开失败 header('Content-Length: '. strlen($str)); Header::connectionClose(); ob_start(); echo $str; ob_flush(); flush(); }</code>
补充说明下:
对于 apache 一般没什问题,我一开始在 windows 上用的 xampp 调试的 没发现什么问题,结果到服务器上是 Nginx ,死活不行,崩溃了一下午,后来才反映过来是 Nginx 的 fastcgi_buffer 的问题。
各种情况测试了N多次,应该没什么 BUG 了。。。
另外再说说 ignore_user_abort() 函数的问题
当浏览器关闭后,决定程序是否还会在后台继续执行,(下图的例子中,你在测试时不一定非要设置为永不超时 limit 0 ,设置一两分钟就行了,否则可能重启 HTTP 服务需要很长时间)
简单来说,如果你要用户浏览器关闭后还需要程序继续执行,那么你必须加上下面这句代码:
<code bash="" class="hljs">ignore_user_abort(true);</code>
但根据你后面程序(主要是 while 死循环)的情况不同而有些许不同:
一般在程序中你可以监控连接状态进行控制:
<code bash="" class="hljs">$isAborted = connection_aborted(); $status = connection_status(); if (0 !== $status || $isAborted) { break; }</code>
但这两个函数要想正常工作得有个前提,就是你的程序必须要有输出内容,且大于当前WebServer 的输出缓存,这样才会起作用。
如果你只是简单的输出一个空格 echo ’ ‘; 可能得循环几千次才会判断到,所以为了更即时的检测到状态你必须每次循环时输出足够多的内容才会触发状态检测。
所以这里也经常会遇到一个问题:当浏览器断开后,即使没有使用 ignore_user_abort(true); 但因为没有任何输出,导致程序仍然会继续执行,死循环会一直跑,如果设置了超时那还好,否则就真死掉了。
下面贴上测试代码(贴个图主要是为了防盗 嘿嘿~)
<code bash="" class="hljs">set_time_limit(0); ignore_user_abort(true); while (1) { echo str_repeat(' ', 65536); $isAborted = connection_aborted(); $status = connection_status(); file_put_contents('test.txt', 'time: '. time() .'; abroted:'. $isAborted .'; status: '. $status); if (0 !== $status || $isAborted) { break; } sleep(2); }</code>
你可以试试注释掉这句
// echo str_repeat(’ ‘, 65536);
另外
set_time_limit(0); 最好也别用 0

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

The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

Are you worried about WordPress backend garbled code? Try these solutions, specific code examples are required. With the widespread application of WordPress in website construction, many users may encounter the problem of garbled code in the WordPress backend. This kind of problem will cause the background management interface to display garbled characters, causing great trouble to users. This article will introduce some common solutions to help users solve the trouble of garbled characters in the WordPress backend. Modify the wp-config.php file and open wp-config.

Title: Discuz background account login exception, how to deal with it? When you use the backend management of the Discuz forum system, you may sometimes encounter abnormal account login. This could be due to a variety of reasons, including a wrong password, account being blocked, network connection issues, etc. When encountering this situation, we need to solve the problem through simple troubleshooting and processing. Check whether the account number and password are correct: First, confirm whether the account number and password you entered are correct. When logging in, make sure the capitalization is correct and the password is

How to disable software from running in the background in win11? We are using some software. When we are not using it, we will close the software. Some software will still run in the background after it is closed. During the process of running in the background, the computer will cause a certain amount of lag. Some friends want to know what should be done. How to disable software from running in the background in win11. The editor below has compiled the steps to disable software from running in the background in Win11. If you are interested, follow the editor and take a look below! Steps to disable software running in the background in win11: 1. Press the shortcut key "win+X" and select "Settings" from the options given above. 2. After entering the new interface, click "Apps" and then find "Applications and Features" on the right. 3. In it, find “Microsoft Information” and click

Discuz background login failed? Teach you how to solve it easily! As Discuz, as a popular forum platform, is widely used in website construction and management, sometimes you will encounter backend login failures, which is troubling. Today we will discuss the issues that may cause Discuz backend login failure, provide some solutions, and attach specific code examples. I hope this article can help webmasters and developers who encounter similar problems. 1. Troubleshooting is to solve the problem of Discuz background login failure.

Switching between different applications is achieved through the front and back switching of processes. Background: After Linux starts a program, it switches to the background for execution and wants to continue operating in Linux. In Linux, you can use the following methods to start and exit a program in the background, but still keep its process running: 1. Linux starts a program to execute in the background 1. Use nohup and &: $nohupyour_program& Use the nohup command to make The program ignores the hang-up signal (SIGHUP) so that the program continues to run even if you exit the terminal. The & symbol causes the program to run in the background. 2. Use ctrl+Z: If you have started the program in the foreground, you can use ct

How to correctly use nohup for background task processing In daily work, we often need to perform some time-consuming tasks, such as file copying, data processing, etc. In order not to affect our work efficiency and ensure that tasks can run stably in the background, we can use the nohup command to start these tasks. This article will introduce how to correctly use nohup for background task processing. What is nohup command? nohup is a command in Unix and Unix-like operating systems that is used to run commands or scripts in the background.

ThinkPHP6 backend management system development: Implementing backend functions Introduction: With the continuous development of Internet technology and market demand, more and more enterprises and organizations need an efficient, safe, and flexible backend management system to manage business data and conduct operational management. This article will use the ThinkPHP6 framework to demonstrate through examples how to develop a simple but practical backend management system, including basic functions such as permission control, data addition, deletion, modification and query. Environment preparation Before starting, we need to install PHP, MySQL, Com
