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 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决