关闭浏览器可以终止服务器上的PHP脚本吗? [英] Can closing the browser terminate the PHP script on the server?

查看:185
本文介绍了关闭浏览器可以终止服务器上的PHP脚本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设用户单击了一个按钮,这导致将jquery ajax请求发送到我的服务器.

Say a user clicked a button, which resulted in a jquery ajax request being sent to my server.

服务器响应ajax请求而开始一个复杂的过程.可以说该过程需要5分钟才能完成.

The server begins a complicated process in response to the ajax request. Lets say that process takes 5 minutes to finish.

与此同时,用户感到无聊并关闭了浏览器窗口.

In the meantime the user gets bored and closes his browser window.

服务器上的脚本会继续处理,直到在正常时间结束,否则会停止吗?

Will the script on the server continue its processing until it finishes on its normal time, or will it stop?

如果用户访问url,例如example.com/process.php?data=xxx,则与此相同.这将启动process.php并开始处理数据,并且需要5分钟才能完成处理.

Same thing if the user visits a url, e.g example.com/process.php?data=xxx. This starts process.php which begins to process the data, and will take 5 mins to finish processing.

此处理将始终继续吗?或者,如果用户关闭浏览器,它将停止吗?

Will this processing always continue on, or if the user closes the browser, will it stop?

(我问,是因为我担心该过程会半途而废,导致数据损坏).

(I'm asking because I'm concerned about the process being left half finished and resulting in corrupt data).

推荐答案

PHP不会注意到浏览器关闭了该连接,除非它尝试输出某些内容(例如echo).如果无法输出内容,除非 ignore_user_abort 处于打开状态,否则脚本将终止.

PHP won't notice that the browser closed the connection unless it tries to output something (e.g. echo). If it fails to output something, the script will be terminated unless ignore_user_abort is On.

因此,只有满足以下条件,脚本才会终止:

So the script will terminate only if the following conditions are met:

  • 该脚本尝试输出某些内容(因为该脚本直到那时才注意到用户中止了连接)
  • 并且php的 ignore_user_abort 设置已关闭(如果该设置已关闭,则php将在失败时终止脚本输出一些东西)

您可以通过启用 ignore_user_abort 来避免脚本终止.

You can avoid the script from terminating by enabling ignore_user_abort.

您可以随时使用 connection_aborted() 来检查是否浏览器中止了请求.

You can use connection_aborted() at anytime to check is the browser aborted the request.

脚本可能由于其他原因(例如最大执行时间,异常等)而意外终止;因此您应该利用事务,以便在脚本异常终止时取消半完成的更改.

A script can terminate unexpectedly for other reasons (e.g. max execution time, exception, etc); so you should make use of transactions, so that half-finished changes are canceled if the script terminates abnormally.

这篇关于关闭浏览器可以终止服务器上的PHP脚本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆