gpt4 book ai didi

php - 重定向但仍继续处理 exec()

转载 作者:可可西里 更新时间:2023-10-31 23:45:48 26 4
gpt4 key购买 nike

此代码示例应该重定向并继续处理长时间的操作,但是直到 exec 命令完成后它才会重定向。我已经尝试了多种其他方法来做到这一点,但没有任何效果。我哪里错了?

在我的 php.ini 中启用了 ignore_user_abort()

<?php
set_time_limit ( 0 );
header ( 'Connection: close' );
ob_start ();
header ( 'Content-Length: 0' );
header ( 'Location: /redirect.php' );
ob_end_flush ();
flush ();
ignore_user_abort ( true );

exec('command that takes 5 minutes to process');
exit ();
?>

在此先感谢您的帮助。

最佳答案

我最近不得不编写一个 webhook 处理程序,它应该在继续处理其他长时间运行的任务之前立即返回“200 OK”响应。

我观察到当整个过程都在使用同一个网络服务器时,立即挂断过程是不可能的。因此,如果您需要发送响应的连接的客户端 IP 与服务器 IP 相同,您可能永远无法做到这一点。但当传入连接是真实世界的远程客户端时,它总是有效。

尽管如此,我只是返回了“200 OK”响应。这应该与发回重定向没有什么不同。

对我有用的代码是......

public function respondASAP($responseCode = 200)
{
// check if fastcgi_finish_request is callable
if (is_callable('fastcgi_finish_request')) {
/*
* This works in Nginx but the next approach not
*/
session_write_close();
fastcgi_finish_request();

return;
}

ignore_user_abort(true);

ob_start();
http_response_code($responseCode);
header('Content-Encoding: none');
header('Content-Length: '.ob_get_length());
header('Connection: close');

ob_end_flush();
ob_flush();
flush();
}

您可以根据您的情况调整它并设置重定向 header 而不是“200 OK”。

关于php - 重定向但仍继续处理 exec(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38151610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com