如何在 PHP 调用的 shell 脚本中访问环境变量?
以下是我在 Apache VirtualHost 容器中设置变量的方法
SetEnv MY_VAR "/opt/"
现在,PHP 可以完美访问该变量:
echo $_SERVER['MY_VAR'];
/opt/
但是,如果我从 PHP 代码调用 shell 脚本
passthru('/path/to/myscript');
MY_VAR
在 /path/ 中为空到/myscript
。
但是,如果我像这样修改调用,它就会起作用:
passthru('export MY_VAR='. $_SERVER['MY_VAR'] .'; /path/to/myscript');
Is there a better way to pass allenvironmentvariables to the shell script?因为我需要通过多个。
我还尝试了 system(),exec(),反引号和 shell_exec()。它们都显示相同的行为,如 passthru()。
Here is how I set the variable within my Apaches VirtualHost Container
SetEnv MY_VAR "/opt/"
Now, PHP can perfectly access this vairable:
echo $_SERVER['MY_VAR'];
/opt/
However, if I call a shell script from my PHP code
passthru('/path/to/myscript');
MY_VAR
is empty within /path/to/myscript
.
If I however modify the call like this, it works:
passthru('export MY_VAR='. $_SERVER['MY_VAR'] .'; /path/to/myscript');
Is there a better way to pass all environment variables to the shell script? Since I need to pass multiple ones.
I also tried system(), exec(), backticks and shell_exec(). They all show the same behavior, as passthru().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用 putenv("MY_VAR=test"); 环境值将传递给调用的 shell 命令。 (但它没有放在
$_ENV
中)所以你可以简单地做类似的事情
If you use
putenv("MY_VAR=test");
the environment value is passed on to the invoked shell command. (but it is not put in$_ENV
)So you could simply do something like
尝试 proc_open。
您可以传递带有环境变量的数组作为选项。
Try proc_open.
You could pass an array with the environment variables as an option.
如果您在首页中使用 phpinfo(),您将看到您的环境变量 (MY_VAR) 未列在“环境”框中,而是列在“Apache 环境”中(如果这是您使用的网络服务器)。
因此,似乎“getenv”不仅从环境中获取其值,还从 Apache 环境中获取其值,而通过 passthru 启动某些内容时(似乎)不会继承该环境。
在 passthru 执行的脚本中,我只看到 env。变量列在“环境”框中,因此它是一致的。
因此,对于要导出到 passthru 脚本的每个变量,您应该使用:
使用数组和 for 循环即可轻松完成。
If you use phpinfo() in your first page, you will see that your env variable (MY_VAR) is not listed in the "Environment" box, but in the "Apache Environment" (if this is the webserver you use).
So, it seems that "getenv" not only gets its values from the environment, but also from Apache environment, which (it seems) is not inherited when launching something by passthru.
In the script executed by passthru, I only see env. vars listed in the "Environment" box, so it is consistent.
So, for each variable you want to export to the passthru script, you should use:
Easy to do with an array and a for loop.
我猜这是因为当您调用 SetEnv 时,您正在修改当前的 shell 环境。当您随后调用 passthru 时,现有的环境以及任何非导出的变量都会被销毁,并且为 /path/to/myscript 提供“新鲜”环境。
您可以在命令行上将环境变量作为参数传递给 /path/to/myscript -MY_VAR=/opt 吗?
I guess it's because when you call SetEnv you're modifing your current shell environment. When you subsequently when you call passthru, your existing env is destroyed along with any non exported variables, and a "fresh" environment given to /path/to/myscript.
Can you instead pass env variables on the command line, as parameters to the /path/to/myscript -MY_VAR=/opt ?