14

I want to set an environment-variable, then access it in PHP, but cannot find how to do so.

In the (linux) shell, I run:

$ APP_ENV="development"
$ export $APP_ENV

Then I run a simple test script testenv.php:

<?php
print $_ENV["APP_ENV"];
print getenv("APP_ENV");

From the same shell where that variable was set:

$ php testenv.php

This Prints nothing and throws a notice:

Notice: Undefined index: APP_ENV in /xxxx/envtest.php on line 2

Notice makes sense, because APP_ENV is simply not found in the environment-variables, getenv() throws no warning but simply returns nothing.

What am I missing?

2 Answers 2

17

Don't use $ in the export command, it should be:

export APP_ENV

You can combine this with the assignment:

export APP_ENV="development"

With the $, you were effectively doing:

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

3 Comments

i think OP included the "$" merely to emphasize that those lines are shell commands.
@cuewizchris I'm not talking about the $ before export, I'm talking about the one after it.
@cuewizchris actually no Barmar is correct export $APP_ENV shouldn't have a $ in front
12
+200

Problem 1 Exporting environment variables

Your export is incorrect.

$ APP_ENV="development"
$ export APP_ENV

Notice that the $ is missing from the export statement! :P

First check getenv to make sure that export works:

<?php
  echo getenv ("APP_ENV");
?>

Problem 2: Undefined index on this:

<?php
   echo $_ENV["APP_ENV"];
?>

If you get a proper value from getenv but not the superglobal $_ENV then you may have to check your ini file.

Quoting php.org:

If your $_ENV array is mysteriously empty, but you still see the variables when calling getenv() or in your phpinfo(), check your http://us.php.net/manual/en/ini.core.php#ini.variables-order ini setting to ensure it includes "E" in the string.

2 Comments

My problem was that variables_order did not include E and I don't think I would've found that myself. Great catch!
If you're only reading that on the next command, you can set and run without exporting as exporting will set the variable available for the whole session: APP_ENV="development" php testenv.php

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.