简体   繁体   English

如何在PHP shell_exec中设置命令行环境变量

[英]How to set command line environment variable in PHP shell_exec

The script I am trying to run via shell_exec in PHP requires an environmental variable to be set, which afaik is done via: 我试图通过PHP中的shell_exec运行的脚本需要设置一个环境变量,其中afaik通过以下方式完成:

export VARIABLE=value

However, to run the script I am forced to do: 但是,要运行脚本,我不得不这样做:

<?PHP
$sOutput = shell_exec("export VARIABLE=value && my_command_goeth_hereth");

It seams kinda pointless to have to export the variable every time I run any commands. 每次运行任何命令时,它都必须导出变量。

Is this the only way to do it, or am I missing a much simpler way? 这是唯一的方法吗,还是我错过了一个更简单的方法?

Since environment variables are inherited, setting them inside your script will set them for the commands it launches too. 由于环境变量是继承的,因此在脚本中设置它们也会为它启动的命令设置它们。 You just have to use putenv . 你只需要使用putenv

putenv("VARIABLE=value");

Won't just: 不仅仅是:

<?PHP
shell_exec('SOMEVAR=SOMEVAL /some/program');

do the trick? 做诀窍?

If you're running multiple shell scripts, then putenv is your friend, as zneak pointed out. 如果你运行多个shell脚本,然后运行putenv是你的朋友,因为zneak指出。

EDIT with an exmaple: 编辑与exmaple:

env.php: env.php:

<?PHP
echo $_ENV['FOO'];
echo "\n";

runenv.php: runenv.php:

<?PHP
echo shell_exec('FOO=bar php env.php');

then try $ php runenv.php 然后尝试$ php runenv.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM