php - 如何从 PHP 调用 bash 函数?

标签 php bash

这是我的工作流程:

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

是否可以更改 php 脚本(或者可能是其调用)的方式,以便它打印“1”?我正在寻找一种从 php 调用 bash 函数的方法。

我在这里尝试了一些解决方案:Is it possible to source a *.sh file using PHP CLI and access exported Env vars in the PHP script?

其中之一是:./test.sh && php -f test.php - 但没有运气。

最佳答案

这是一个可以完成您想要的功能的函数。它加载并生成一个 bash 进程,该进程获取 bash 脚本,然后运行该函数。

它使用 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\n");
            fwrite($pipes[0], "$bashfunction\n");
            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;
}
?>

关于php - 如何从 PHP 调用 bash 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33468438/

相关文章:

linux - 在 linux 中使用 cl1p.net 在线剪贴板的 shell 脚本 - 错误 (23) 写入正文失败

php - 从数据库中获取集合类型字段 - Agile Toolkit

php - Paypal: Invalid IPN 问题

javascript - 如何在WordPress内容(single.php)中添加自动折叠/展开?

bash - 在 openvpn 中为 SSL-Key 传递密码

bash - 打印两个模式之间的所有行,独占的,仅限第一个实例(在 sed、AWK 或 Perl 中)

javascript - 实时检查用户可用性 LDAP

php - 三元运算符中的多个条件安全吗?

linux - 复制最近 14 天内修改过的文件

linux - 有人可以向我解释这些 "sed"命令以及它们在做什么吗?