这是我的工作流程:
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/