Export shell environment variable before running command from PHP CLI script

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 not be able to find the libraries.

I tried the following:

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

Using putenv () does not apply to the command I am running. He does not say that he cannot find it in 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 to set a shell variable from PHP that extends to the child processes of my PHP script?

I am limited to checking if a variable exists in the current environment and asking the user to manually set it?

+6
source share
3 answers

I'm not 100% familiar with how PHP exec works, but 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 does something.

EDIT: suppose this works to deal with multiple variables, just separate them with a space:

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

+5
source

You can simply add 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 ~]$ 
+2
source

A couple of things come to mind. One for $ cmd should be a script that includes setting the environment variable before running the real program.

Another thought is this: I know that you can define a variable and run the program on one line, for example:

 DISPLAY=host:0.0 xclock 

but I don't know if this works in the context of passthru

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

+1
source

Source: https://habr.com/ru/post/910357/


All Articles