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条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。