5

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

First, I've tried putenv(), but this gives no result:

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

$

When i call getenv() from the same script — it results in the right 'string' value. Safe mode is off, but the manual says 'PHP_' prefix is vital with safe=on so I use it just in case :)

Then I 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 might be the reason? I'm using Ubuntu Linux 9.10 "Karmic", but FreeBSD server gives the same result.

2 Answers 2

3

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

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

Showing how export affects 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 shown is a child (and siblings of each other).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That makes the question clear. But then, how getopt (and some other non-builtin programs) manage to export variables to the outer context? (E.g. getopt exports $OPTIND)
You're confusing the external /usr/bin/getopt which doesn't and can't do that with the builtin getopts which does.
2

Environment variables that are exported are only available in child processes.

So you'll be able to set an environment variable and then spawn a child process. The environment variable will be visible in that child process. However setting it in php and then launching a successive process (echo, in your example above) won't work.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.