export shell environment variable before running command from PHP CLI script

馋奶兔 提交于 2019-12-07 02:47:12

问题


I have a script that uses passthru() to run a command. I need to set some shell environment variables before running this command, otherwise it will fail to find it's libraries.

I've tried the following:

putenv("LD_LIBRARY_PATH=/path/to/lib");
passthru($cmd);

Using putenv() doesn't appear to propagate to the command I'm running. It fails saying it can't find it libraries. When I run export LD_LIBRARY_PATH=/path/to/lib in bash, it works fine.

I also tried the following (in vain):

exec("export LD_LIBRARY_PATH=/path/to/lib");
passthru($cmd);

How can I set a shell variable from PHP, that propagates to child processes of my PHP script?

Am I limited to checking if a variable does not exist in the current environment and asking the user to manually set it?


回答1:


I'm not 100% familiar with how PHP's exec works, but have you tried: exec("LD_LIBRARY_PATH=/path/to/lib $cmd")

I know that this works in most shells but I'm not sure how PHP doing things.

EDIT: Assuming this is working, to deal with multiple variables just separate them by a space:

exec("VAR1=val1 VAR2=val2 LD_LIBRARY_PATH=/path/to/lib $cmd")




回答2:


You could just prepend your variable assignments to $cmd.

[ghoti@pc ~]$ cat doit.php 
<?php

$cmd='echo "output=$FOO/$BAR"';

$cmd="FOO=bar;BAR=baz;" . $cmd;

print ">> $cmd\n";
passthru($cmd);

[ghoti@pc ~]$ php doit.php 
>> FOO=bar;BAR=baz;echo "output=$FOO/$BAR"
output=bar/baz
[ghoti@pc ~]$ 



回答3:


A couple things come to mind. One is for $cmd to be a script that includes the environment variable setup before running the actual program.

Another thought is this: I know you can define a variable and run a program on the same line, such as:

DISPLAY=host:0.0 xclock

but I don't know if that work in the context of passthru

https://help.ubuntu.com/community/EnvironmentVariables#Bash.27s_quick_assignment_and_inheritance_trick



来源:https://stackoverflow.com/questions/9636605/export-shell-environment-variable-before-running-command-from-php-cli-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!