如何在 PHP exec 函数中显示进度条

How to display progress bar in PHP exec functions

我是 运行 PHP 中的外部脚本,使用其 exec() 功能。我一直在寻找各种选项来创建进度条。我可以通过 AJAX 创建一个普通的旋转加载器,但我无法实现百分比进度条。有什么办法吗?

PHP 在服务器上运行,因此无法实现(据我所知), 以下是一些可能对您有所帮助的已回答问题。

How to show loading status in percentage for ajax response?
Jquery:: Ajax powered progress bar?

根据您要执行的程序,您可以使用 proc_open() instead of exec(), so you can proccess the output, calculate a percentage and throw it back to your ajax script using ob_flush() and flush()

在发送任何输出之前需要等待执行完成是不正确的,但是您的服务器缓存配置和浏览器渲染引擎有一些警告,所以它不是那么可靠。

如果您不使用 Websockets(干净和现代的选项,可以通过 PHP 使用 Ratchet 或使用 nodejs 使用各种选项来实现),最可靠的方法是做什么你想要的是轮询。

简而言之,您不是调用脚本一次,而是先 ajax 请求初始化进程,然后开始一次又一次地戳服务器以询问脚本的执行状态。

有关更多信息,请查看这些答案:

Run process with realtime output in PHP

PHP - Flushing While Loop Data with Ajax

Grab results from a php exec() while the command is still running?