dragon0023 2015-11-01 23:27
浏览 117
已采纳

如何从PHP调用bash函数?

This is my workflow:

ubuntu$ cat test.sh
#!/bin/bash

function getNumber
{
    echo 1
}


ubuntu$ cat test.php
<?php

echo shell_exec("getNumber");



ubuntu$ source test.sh 
ubuntu$ getNumber 
1

ubuntu$ php test.php 
sh: 1: getNumber: not found

Is it possible to change a php script (or may be its call) the way, so it will print "1"? I am looking for a way to call a bash function from php.

I've tried some solutions from here: Is it possible to source a *.sh file using PHP CLI and access exported Env vars in the PHP script?

One of them was: ./test.sh && php -f test.php - but no luck.

  • 写回答

4条回答 默认 最新

  • dqn8235 2015-11-02 00:53
    关注

    Here's a function that does what you want. It loads spawns a bash process that sources the bash script, then runs the function.

    It uses proc-open ( http://php.net/manual/en/function.proc-open.php )

    <?php
    
    
    $value = runBashFunction("test.sh", "getNumber");
    var_dump($value);
    
    
    
    function runBashFunction($bashfile, $bashfunction) {
        $descriptorspec = array(
             0 => array("pipe", "r"),    // stdin is a pipe that the child will read from
             1 => array("pipe", "w"),    // stdout is a pipe that the child will write to
             2 => array("pipe", "w") // stderr is a pipe too
        );
    
        $cwd = '.';
        $env = array();
    
        $process = proc_open('bash', $descriptorspec, $pipes, $cwd, $env);
    
        if (is_resource($process)) {
                fwrite($pipes[0], "source $bashfile
    ");
                fwrite($pipes[0], "$bashfunction
    ");
                fclose($pipes[0]);
    
                $output = stream_get_contents($pipes[1]);
                $error = stream_get_contents($pipes[2]);
                fclose($pipes[1]);
                fclose($pipes[2]);
    
                // It is important that you close any pipes before calling
                // proc_close in order to avoid a deadlock
                //
    
                $return_value = proc_close($process);
                //note, $error and $return_value are discarded
                return $output;
        }
        return null;
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境