I have a very expensive query which gets executed from php and it can take a while to execute. Is there a way, in php, to detect if a user disconnects prior to the query being done and cancel it?
2条回答 默认 最新
- duankao4489 2012-03-20 18:31关注
A possible solution is to use pg_send_query(), that function sends a query to the database and returns immediatly without blocking. Then you can poll to see if the user disconnected before the query finished. See this:
ignore_user_abort(false); $db = pg_connect(DATABASE_DSN); pg_send_query($db, "SELECT pg_sleep(10000)"); // long running query while(pg_connection_busy($db)) { /* You need to output something to the browser so PHP can know when the browser disconnected. The 0 character will be ignored. */ echo chr(0); /* Need to do both flushes to make sure the chr is sent to the browser */ ob_flush(); flush(); usleep(100000); // 0.1s to avoid starving the CPU if(connection_status() != CONNECTION_NORMAL || connection_aborted()) { // Browser disconnected, cleanup an die pg_cancel_query($db); pg_query($db, "ROLLBACK"); pg_close($db); die(); } } // At this point the query finished and you can continue fetching the rows
This approach works but has a big problem: you really need to send something to the browser to detect the browser disconnection. If you don't, connection_status() and connection_aborted() will not work. This seems to be an old PHP bug, see here: https://bugs.php.net/bug.php?id=30301
So this method doesn't work when, for example, you query Postgres in the middle of a PDF generation routine. In that case the needed chr(0) will break the generated binary file.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
- ¥15 Python卡尔曼滤波融合
- ¥20 iOS绕地区网络检测
- ¥15 python验证码滑块图像识别
- ¥15 根据背景及设计要求撰写设计报告
- ¥20 能提供一下思路或者代码吗
- ¥15 用twincat控制!
- ¥15 请问一下这个运行结果是怎么来的
- ¥15 单通道放大电路的工作原理
- ¥30 YOLO检测微调结果p为1