Export variable from PHP to shell

I am trying to set a variable that should be accessible from outside of PHP. Ideally, this should be a local variable, but environment variables are also welcome.

Firstly, I tried putenv() , but this does not work:

$ php -r "putenv ('PHP_TEST = string');"; echo $ PHP_TEST

$

When I call getenv() from the same script, this results in the correct string value. Safe mode is disabled, but the manual says that the prefix "PHP_" is vital with security =, so I use it just in case :)

Then I will try system() or shell_exec() :

$ php -r "shell_exec ('PHP_TEST = string');"; echo $ PHP_TEST

$ php -r "shell_exec ('export PHP_TEST = string');"; echo $ PHP_TEST

$

Is there a workaround? what could be the reason? I am using Ubuntu Linux 9.10 "Karmic", but the FreeBSD server gives the same result.

+5
source share
2 answers

If you are trying to pass some output to a shell variable, you can do it like this:

 $ testvar=$(php -r 'print "hello"') $ echo $testvar hello 

Display the effect of exports on things:

 $ php -r '$a=getenv("testvar"); print $a;' $ export testvar $ php -r '$a=getenv("testvar"); print $a;' hello 

In these examples, the interactive shell is the parent process, and everything else is the child process (and brothers and sisters from each other).

+3
source

Exported environment variables are only available in child processes.

This way you can set the environment variable and then create a child process. The environment variable will be visible in this child process. However, installing it in php and then starting a sequential process ( echo , in your example above) will not work.

If you set a variable and then spawn / exec a new process, it should be visible in this new process.

+2
source

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


All Articles