javascript - PHP 在 HTML 中显示实时 Shell 输出

标签 javascript php html bash shell

我有一个 shell 文件 shell.sh,每 1 秒回显 hi 一次。我想在我的网站上的一个框中显示 shell 脚本的实时输出。

但是,问题是,我的代码没有在框中显示输出。当我点击它时,所有内容都会消失,我只看到一个白色页面。

以下是我的 php 文件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <form method="GET" action="splitter.php">
        <label for="folderPath">Folder Path:</label>
        <input type="text" id="folderPath" name="folderPath">
    <br></br>
        <fieldset id="khz">
            <p>Please Choose Khz: </p>
          <input type="radio" value="8khz" name="khz"> 8khz <br>
          <input type="radio" value="16khz" name="khz"> 16khz <br>
        </fieldset>
    <br></br>
        <fieldset id="audio-type">
            <p>Please Choose Type: </p>
          <input type="radio" value="C12" name="group2"> Channel 1 & 2 <br>
          <input type="radio" value="LR" name="group2"> Left to Right <br>
        </fieldset>
        <div class="spaceh10"></div>
        <input class = "submitButton" type="submit" value="Submit">

    <div class="spaceh10"></div>
    <div style="width:500px;height:100px;border:1px solid #000;">
    <?php
    if (isset($_GET['folderPath']) && !empty($_GET['folderPath']) && 
    isset($_GET['khz']) && isset($_GET['group2'])) {

    $folderPath = $_GET['folderPath'];
    $khz = $_GET['khz'];
    $group2 = $_GET['group2'];
    #$folderPath $khz $group2
    $command = './shell.sh';
    while (@ ob_end_flush()); // end all output buffers if any

    $proc = popen($command, 'r');
    echo '<pre>';
    while (!feof($proc)){
        echo fread($proc, 4096);
        @ flush();
    }
    echo '</pre>';
    }
    ?>
    </div>
</body>
</html>

下面是我的 shell 脚本

while true
do 
    echo "Hi"
    sleep 1
done

如何让我的代码在框中运行?并确保输出仅留在框中并且不会溢出。为什么我的代码不显示输出?

我正在监视我的 php 文件正在运行的服务器地址。当我单击“提交”时,它会永远加载在白色屏幕上,因为我知道它不会结束,所以我会在浏览器中停止。 我收到以下错误。

./shell.sh: line 6: echo: write error: Broken pipe

如何在框中显示实时 shell 输出?并且它不会流出框边框?

最佳答案

如果您可以使用节点工具,而不是纯 PHP,请查看 websocketdthis question .

PHP 不是实时应用程序的最佳选择,因为通常 php 应用程序的生命周期很短,但您所要求的是 WebSocket 服务器。或者,如果您确实想使用 php,则可以使用轮询来调用从日志文件读取的 php 端点。

但是,it is possible ,只是不像使用节点(或 Elixir、Go、Ruby 等)那么容易,因为 Node 存在更多此用例的示例。

关于javascript - PHP 在 HTML 中显示实时 Shell 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61667637/

相关文章:

php - 试图让 PHP 和数据库协同工作

ios - Html5 Canvas : Can I draw really sharp on non-retina devices like iPad2?

PHP 表单验证数字字段

javascript从字符串动态创建多维数组

JavaScript/CSS 与 Silverlight 与 Flex

PHP MySQL 将 GROUP_CONCAT 结果视为单独的项目

php - Eloquent 查询多重关系深层

android - Phonegap-从www文件夹加载mp3

java - mongodb mongodump json 日期字段解析错误

javascript - 为什么我应该在 Typescript 中使用接口(interface)