简体   繁体   English

如何使用PHP的实时反馈运行shell脚本?

[英]How to run shell script with live feedback from PHP?

How would I execute a shell script from PHP while giving constant/live feedback to the browser? 如何在向浏览器提供持续/实时反馈的同时从PHP执行shell脚本? I understand from the system function documentation: 我从系统功能文档中了解到:

The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module. 如果PHP作为服务器模块运行,system()调用还会尝试在每行输出后自动刷新Web服务器的输出缓冲区。

I'm not clear on what they mean by running it as a 'server module'. 通过将其作为“服务器模块”运行,我不清楚它们的含义。

Example PHP code: PHP代码示例:

<?php

system('/var/lib/script_test.sh');

Example shell code: 示例shell代码:

#!/bin/bash

echo "Start..."
for i in {1..10}
do
        echo "$i..."
        sleep 1
done
echo "Done."

What this does: It will wait about 10 seconds and then flush to the output buffer. 这样做:它将等待大约10秒,然后刷新到输出缓冲区。

What I want this to do: Flush to the output buffer after each line of output. 我想要这样做:在每行输出后刷新到输出缓冲区。

This can be done using popen() which gives you a handle to the stdout of whatever process you open. 这可以使用popen()来完成,它为您提供了打开任何进程的标准输出的句柄。 Chunks of data can be sent to the client using ob_flush() , the data can be displayed using an XHR. 可以使用ob_flush()将数据块发送到客户端,可以使用XHR显示数据。

One option is to write to a file in the shell script, on each step to say where it's up to. 一种选择是写入shell脚本中的文件,在每一步中说明它的位置。 On your web page, use an ajax call every X seconds/minutes. 在您的网页上,每隔X秒/分钟使用一次ajax调用。 The ajax call will call a PHP script which reads the status file and returns the status or completed steps. ajax调用将调用PHP脚本,该脚本读取状态文件并返回状态或已完成的步骤。

The advantage to this approach is the page live information will be available to multiple visitors, rather than just the one that actually initiated the shell script. 这种方法的优点是页面实时信息可供多个访问者使用,而不仅仅是实际启动shell脚本的访问者。 Obviously that may or may not be desirable depending on your needs. 显然,根据您的需要,可能会或可能不会。

The disadvantage of course is the longer the ajax interval, the more out of date the update will be. 当然缺点是ajax间隔越长,更新过期就越多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM