Question

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().

Was it helpful?

Solution

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

foreach ( $_SERVER as $k=>$v ) putenv("$k=$v");

OTHER TIPS

Try proc_open.

proc_open('/path/to/myscript', $descriptorspec, $pipes, null, $_SERVER);

You could pass an array with the environment variables as an option.

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:

putenv('MY_VAR ='.apache_getenv('MY_VAR'));

Easy to do with an array and a for loop.

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 ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top