exportar la variable de entorno de shell antes de ejecutar el comando desde el script PHP CLI

Tengo un script que usa pasar a través de() 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.

He intentado lo siguiente:


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

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?

preguntado el 09 de marzo de 12 a las 15:03

I've read that question, this looks similar but if you read it, I'm asking how to achieve something different. -

3 Respuestas

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

respondido 09 mar '12, 16:03

And if I have more than one variable? MYVAR=value; LD_LIBRARY_PATH=/path/to/lib $cmd ? - greg k

seems to, at least according to the ubuntu link I posted, though I haven't ever done that - dldnh

Thanks, this works. I had to space separate multiple environment variables. - greg k

You could just prepend your variable assignments to $cmd.

[ghoti@pc ~]$ cat doit.php 

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

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

print ">> $cmd\n";

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

respondido 09 mar '12, 16:03

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


respondido 09 mar '12, 15:03

$cmd is actually a command to run an ant build file, this script wraps construction of that command. - greg k

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.