berkes
berkes

Reputation: 27553

Passing an environment-variable into a php commandline script

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?

Upvotes: 14

Views: 20892

Answers (2)

Ahmed Masud
Ahmed Masud

Reputation: 22372

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.

Upvotes: 12

Barmar
Barmar

Reputation: 780889

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

Upvotes: 17

Related Questions