如果取消/关闭 HTTP 请求,PHP 会自动终止脚本

标签 php ajax

问题是,对于一个很长的过程,无论客户端浏览器当前是否连接,PHP 脚本都会继续执行。是否有可能如果客户端终止了对脚本的 Ajax 调用,那么该脚本也会在服务器上终止?

最佳答案

正如@metadings 所指出的,php 确实有一个名为 connection_aborted() 的检查连接中止的函数。如果连接终止,它将返回 1,否则返回 0。

In a long server side process the user may need to know if the client is disconnected from the server or he has closed the browser then the server can safely shutdown the process.

特别是在应用程序使用 php session 的情况下,如果即使在客户端断开连接后我们仍让长进程继续运行,那么服务器将对该 session 无响应。来自同一客户端的任何其他请求将等待,直到较早的过程完全执行。出现这种情况的原因是进程运行时session文件被锁住了。但是,您可以有意地调用 session_write_close() 方法来解锁它。但这并非在所有情况下都可行,可能需要在流程结束时向 session 写入一些内容。

Now if we only call connection_aborted() in a loop then it will always return 0 whether the connection is closed or not.

0 表示连接未中止。这是误导。但是,经过重新搜索和实验发现是php中的output buffer的原因。

首先,为了检查中止,循环中的开发人员必须通过回显一些文本向客户端发送一些输出。例如:

print " ";

由于该进程仍在运行,因此不会将输出发送到客户端。现在要发送输出,我们需要刷新输出缓冲区。

flush ();
ob_flush ();

然后,如果我们检查中止,它将给出正确的结果。

if (connection_aborted () != 0) {
  die();
}

以下是工作示例,即使您使用的是 PHP session ,它也可以工作:

session_start ();
ignore_user_abort ( TRUE );

file_put_contents ( "con-status.txt", "Process started..\n\n" );

for($i = 1; $i <= 15; $i ++) {

    print " ";

    file_put_contents ( "con-status.txt", "Running process unit $i \n", FILE_APPEND );
    sleep ( 1 );

    // Send output to client
    flush ();
    ob_flush ();

    // Check for connection abort
    if (connection_aborted () != 0) {
        file_put_contents ( "con-status.txt", "\nUser terminated the process", FILE_APPEND );
        die ();
    }

}

file_put_contents ( "con-status.txt", "\nAll units completed.",  FILE_APPEND );

编辑 2017 年 4 月 7 日

If someone is using Fast-Cgi on Windows then he can actually terminate the CGI thread from memory when the connection is aborted using following code:

if (connection_aborted () != 0) { apache_child_terminate(); 导出; }

关于如果取消/关闭 HTTP 请求,PHP 会自动终止脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16524203/

相关文章:

javascript - PHP 脚本 JQuery 获取错误数量的元素

javascript - 无法从 XML 数据完全填充 HTML 表

php - 如何从网站下载 html 的副本?

javascript - JQuery .click 不适用于 php 文件

javascript - 在浏览器中禁用 javascript 会影响 ajax 调用和 js 功能

python - 适用于 Google App Engine 应用程序的任何好的 AJAX 框架?

php - 使用 $.ajax() 响应 if else 语句

javascript - 用户授权/未授权访问网页并导致错误

c# - 来自 PHP 的类未注册错误

php - 以编程方式设置 CSS 背景的最佳方式?