我试图通过PHP中的shell_exec运行的脚本需要设置一个环境变量,其中afaik通过以下方式完成:
export VARIABLE=value
Run Code Online (Sandbox Code Playgroud)
但是,要运行脚本,我不得不这样做:
<?PHP
$sOutput = shell_exec("export VARIABLE=value && my_command_goeth_hereth");
Run Code Online (Sandbox Code Playgroud)
每次运行任何命令时,它都必须导出变量.
这是唯一的方法吗,还是我错过了一个更简单的方法?
zne*_*eak 16
由于环境变量是继承的,因此在脚本中设置它们也会为它启动的命令设置它们.你只需要使用putenv.
putenv("VARIABLE=value");
Run Code Online (Sandbox Code Playgroud)
不仅仅是:
<?PHP
shell_exec('SOMEVAR=SOMEVAL /some/program');
Run Code Online (Sandbox Code Playgroud)
做诀窍?
如果你运行多个shell脚本,然后运行putenv是你的朋友,因为zneak指出.
编辑与exmaple:
env.php:
<?PHP
echo $_ENV['FOO'];
echo "\n";
Run Code Online (Sandbox Code Playgroud)
runenv.php:
<?PHP
echo shell_exec('FOO=bar php env.php');
Run Code Online (Sandbox Code Playgroud)
然后试试
$ php runenv.php