11

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?

Greg K
  • 10,770
  • 10
  • 45
  • 62
  • possible duplicate of http://stackoverflow.com/questions/2002970/export-a-variable-from-php-to-shell – Electronick Mar 09 '12 at 15:32
  • I've read that question, this looks similar but if you read it, I'm asking how to achieve something different. – Greg K Mar 09 '12 at 15:46

3 Answers3

9

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")

gymbrall
  • 2,063
  • 18
  • 21
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 ~]$ 
ghoti
  • 45,319
  • 8
  • 65
  • 104
1

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

dldnh
  • 8,923
  • 3
  • 40
  • 52
  • $cmd is actually a command to run an ant build file, this script wraps construction of that command. – Greg K Mar 09 '12 at 15:45